/**
 * Created by Administrator on 2016/9/18.
 */
define(function (require, exports) {
    var ajaxUtil = require('util/ajaxUtil').ajaxUtil;
    var logUtil = require('util/logUtil').logUtil;
    var commonUtil = require('util/commonUtil').commonUtil;
    var validationUtil = require('util/validationUtil').validationUtil;

    var controls = {};
    controls.app_template_detail_panel = $('#app_template_detail_panel');
    controls.app_scene_detail_panel = $('#app_scene_detail_panel');
    controls.app_template_list_panel = $('#app_template_list_panel');
    controls.app_scene_list_panel = $('#app_scene_list_panel');

    controls.app_scene_preset_detail_panel = $('#app_scene_preset_detail_panel');
    controls.app_scene_preset_list_panel = $('#app_scene_preset_list_panel');

    controls.input_template_upload = $('#input_template_upload');
    controls.input_template_banner_upload = $('#input_template_banner_upload');
    controls.input_template_music_upload = $('#input_template_music_upload');

    controls.app_template_style_detail_panel = $('#app_template_style_detail_panel');
    controls.template_style_edit = $('#template_style_edit');
    controls.template_style_list = $('#template_style_list');

    controls.page_node = $('#page-wrapper');

    controls.app_scene_category_detail_panel = $('#app_scene_category_detail_panel');
    controls.app_scene_category_list_panel = $('#app_scene_category_list_panel');

    controls.input_template_style_upload = $('#input_template_style_upload');

    controls.app_template_color_panel = $('#app_template_color_panel');
    controls.input_template_video_upload = $('#input_template_video_upload');

    controls.app_template_render_success = $('#app_template_render_success');

    controls.input_template_image_upload = $('#input_template_image_upload');
    controls.input_scene_preview_image_upload = $('#input_scene_preview_image_upload');
    controls.input_template_preset_image_upload = $('#input_template_preset_image_upload');
    controls.input_template_preset_video_upload = $('#input_template_preset_video_upload');

    controls.input_template_color_svg_upload = $('#input_template_color_svg_upload');

    // controls.copyright_select = $('#copyright_select');
    controls.template_tool_type = $('#template_tool_type');
    controls.scene_preset_lock = $('#scene_preset_lock');
    controls.app_scene_category_panel = $('#app_scene_category_panel');

    controls.app_scene_preview_image_panel = $('#app_scene_preview_image_panel');
    controls.app_scene_preview_image_panel_node = $('#app_scene_preview_image_panel_node');

    var urls = {};
    urls.template_list = '/admin/template/template-list';
    urls.template_save = '/admin/template/template-save';
    urls.template_del = '/admin/template/template-del';
    urls.template_publish = '/admin/template/template-publish';
    urls.template_set_svg = '/admin/template/template-set-svg';

    urls.scene_list = '/admin/template/scene-list';
    urls.scene_save = '/admin/template/scene-save';
    urls.scene_save_pure = '/admin/template/scene-save-pure';
    urls.scene_render = '/admin/template/scene-render';
    urls.scene_render_state = '/admin/template/scene-render-state';
    urls.scene_del = '/admin/template/scene-del';
    urls.upload_policy = '/admin/file/upload-policy';
    urls.upload_file_key = '/admin/file/upload-file-key';

    urls.preset_list = '/admin/template/preset-list';
    urls.preset_save = '/admin/template/preset-save';
    urls.preset_del = '/admin/template/preset-del';
    urls.template_color = '/admin/template/template-colors';

    urls.app_template_category_query = '/admin/category/template-category-query';
    urls.tag_query = '/admin/category/tag-query';
    urls.scene_category_list = '/admin/category/scene-category-query';
    urls.get_page_part = '/admin/page/get-part';

    urls.save = '/admin/category/scene-category-save';
    urls.list = '/admin/category/scene-category-query';
    urls.delete = '/admin/category/scene-category-del';

    var setting = {
        view: {
            selectedMulti: false
        },
        check: {
            enable: true,
            chkboxType: {"Y": "ps", "N": "ps"}
        },

        data: {
            simpleData: {
                enable: true
            }
        }
    };

    var G_MODIFY_TEMPLATE = false;
    var G_CURRENT_DATA_TEMPLATE = null;

    var G_MODIFY_SCENE = false;
    var G_CURRENT_DATA_SCENE = null;

    var G_MODIFY_PRESET = false;
    var G_CURRENT_DATA_PRESET = null;

    var LIST_BOX = null;

    var G_TEMPLATE_BANNER_URL = null;
    var G_TEMPLATE_IMAGE_URL = null;

    var G_TEMPLATE_VIDEO_URL = null;
    var G_TEMPLATE_STYLE_IMAGE_URL = null;
    var G_SCENE_MUSIC = [];

    var G_DEIT_STYLE = false;
    var G_EDIT_ID = null;

    var G_TEMPLATE_COLORS = [];
    var G_TEMPLATE_COLORITEMS = [];
    var G_CURRENT_COLOR_DATA = null;

    var G_CURRENT_RENDER_ITEM = null;

    var G_TIMER = false;

    var PRESET_IMAGE_URL = null;
    var PRESET_VIDEO_URL = null;

    var G_ALL_SCENE_CATEGORY = null;

    var G_MODIFY_CATEGORY_SCENE = false;
    var G_CURRENT_DATA_CATEGORY_SCENE = null;

    var G_IS_SCENE_LOAD = false;
    var G_IS_SCENE_CATETORY_LOAD = false;
    var G_IS_SCENE_PERSET_LOAD = false;

    var G_SCENE_PREVIEW_IMAGE = null;

    var G_POINTS = {};
    var G_POINTS_ORI = {};
    var polygons = {};
    var canvas = null;

    var G_UPLOAD_POLICY = null;


    function init() {
        bindEvent();
        loadTemplateData();
        initCategoriesList();
        loadSceneData();
        loadPresetData();

        var time = new Date().getTime();
        window.TIME_LOCK = time;
        controls.app_template_list_panel.attr('timelock', time);

        ajaxUtil.doAjaxGet(urls.upload_policy).done(function(ret) {
            if(ret.status === 0) {
                G_UPLOAD_POLICY = ret.data;
            }
        });

        setTimeout(function () {
            var _callee = arguments.callee;
            if (G_TIMER && (window.TIME_LOCK == controls.app_template_list_panel.attr('timelock'))) {
                let taskIds = [];
                $("#app_scene_list_grid").find('.resource-status-render').each(function () {
                    var data = JSON.parse(decodeURIComponent($(this).data('user')));
                    if (data.status != 1) {
                        taskIds.push(data.task_id);
                    }
                });

                console.log(taskIds);

                if (taskIds.length > 0) {
                    ajaxUtil.doAjaxGet(urls.scene_render_state, {
                        id: taskIds.filter(function (item) {
                            return !!item
                        }).join(',')
                    }, false).done(function (ret) {
                        if (ret.status == 0) {
                            let retObj = JSON.parse(ret.data);

                            if (retObj.status != 200) {
                                commonUtil.toast(retObj.err);
                            } else {
                                $("#app_scene_list_grid").find('.resource-status-render').each(function () {
                                    var _self = this;
                                    var innerData = JSON.parse(decodeURIComponent($(this).data('user')));
                                    console.log(innerData);
                                    for (var i = 0; i < retObj.data.length; i++) {
                                        if (retObj.data[i].batchId == innerData.task_id) {
                                            $(_self).text(retObj.data[i].curStep + ',' + retObj.data[i].progress + '%');
                                            if (retObj.data[i].progress == 100) {
                                                $(_self).parent().prev().find('a:eq(0)').text('渲染完成');
                                                $(_self).parent().prev().find('a:eq(0)').removeClass('resource-status').addClass('resource-render-success')
                                                refreshSceneData();
                                            }

                                            if(retObj.data[i].state=='fail') {
                                                $(_self).parent().prev().find('a:eq(0)').html('<span style="color:red">渲染失败</span>');
                                            }
                                        }
                                    }
                                });
                            }
                        } else {
                            commonUtil.toast(ret.msg);
                        }

                        setTimeout(_callee, 5000);
                    });
                } else {
                    setTimeout(_callee, 5000);
                }


            } else {
                console.log('no no no ...');
                setTimeout(_callee, 5000);
            }
        }, 5000)
    }

    function hexToRgb(hex) {
        var result = /^#?([a-fd]{2})([a-fd]{2})([a-fd]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    }

    function initListBox(data) {
        if (data) {
            data = JSON.parse(data);
        } else {
            data = [];
        }

        ajaxUtil.doAjaxGet(urls.scene_list, {template_id: G_CURRENT_DATA_TEMPLATE.id,type:0}).done(function (ret) {
            if (ret.status == 0) {
                controls.app_scene_preset_detail_panel.find('.listbox_scene:eq(0)').empty();
                for (var i = 0; i < ret.data.rows.length; i++) {
                    var flag = false;
                    for (var j = 0; j < data.length; j++) {
                        if (data[j].id == ret.data.rows[i].id) {
                            flag = true;
                            controls.app_scene_preset_detail_panel.find('.listbox_scene:eq(0)').append('<option selected="selected" value="' + ret.data.rows[i].id + '">' + ret.data.rows[i].title + '</option>')
                            break;
                        }
                    }

                    if (!flag) {
                        controls.app_scene_preset_detail_panel.find('.listbox_scene:eq(0)').append('<option value="' + ret.data.rows[i].id + '">' + ret.data.rows[i].title + '</option>')

                    }
                }

                LIST_BOX = $('.listbox_scene').bootstrapDualListbox({
                    nonSelectedListLabel: '未选择的场景',
                    selectedListLabel: '已选择场景',
                    // preserveSelectionOnMove: 'moved',
                    // moveOnSelect: false,
                });

                LIST_BOX.bootstrapDualListbox('refresh');

            }
        });

    }

    function initCategoriesList() {
        ajaxUtil.doAjaxGet(urls.app_template_category_query, null).done(function (ret) {
            if (ret.status == 0) {
                controls.app_template_list_panel.find('select:eq(0)').empty();
                controls.app_template_list_panel.find('select:eq(0)').append('<option value="-1">全部分类</option>');
                for (var i = 0; i < ret.data.length; i++) {
                    controls.app_template_list_panel.find('select:eq(0)').append('<option value="' + ret.data[i].val + '">' + ret.data[i].val + '</option>')
                }
            }
        })
    }

    function initSceneCategoryList() {
        ajaxUtil.doAjaxGet(urls.scene_category_list, {
            page: 1,
            limit: 1000,
            template_id: G_CURRENT_DATA_TEMPLATE.id
        }).done(function (ret) {
            if (ret.status == 0) {
                // controls.app_scene_detail_panel.find('select:eq(0)').empty();
                // controls.app_scene_list_panel.find('select:eq(0)').empty();
                // controls.app_scene_list_panel.find('select:eq(0)').append('<option value="-1">全部分类</option>');
                // for (var i = 0; i < ret.data.rows.length; i++) {
                //     controls.app_scene_detail_panel.find('select:eq(0)').append('<option value="' + ret.data.rows[i].val + '">' + ret.data.rows[i].val + '</option>')
                //     controls.app_scene_list_panel.find('select:eq(0)').append('<option value="' + ret.data.rows[i].val + '">' + ret.data.rows[i].val + '</option>')
                // }

                G_ALL_SCENE_CATEGORY = ret.data.rows;


                $('#app_scene_category_panel_body').empty();
                controls.app_scene_list_panel.find('select:eq(0)').empty();
                controls.app_scene_list_panel.find('select:eq(0)').append('<option value="-1">全部分类</option>');
                for (var i = 0; i < ret.data.rows.length; i++) {
                    $('#app_scene_category_panel_body').append('<div><input type="radio" value="' + ret.data.rows[i].val + '" name="scene_category_radio"/><span style="position: relative;top:-3px;">' + ret.data.rows[i].val + '</span></div>')
                    controls.app_scene_list_panel.find('select:eq(0)').append('<option value="' + ret.data.rows[i].val + '">' + ret.data.rows[i].val + '</option>')
                }
            }
        })
    }

    function showSceneListPanel() {
        controls.app_scene_list_panel.show();
        controls.app_template_list_panel.hide();
        controls.app_scene_detail_panel.hide();
        controls.app_template_color_panel.hide();

        controls.app_scene_category_list_panel.hide();
        controls.app_scene_preview_image_panel.hide();
        initSceneCategoryList();
    }

    function showTemplateListPanel() {
        controls.app_scene_list_panel.hide();
        controls.app_template_list_panel.show();
        controls.app_scene_detail_panel.hide();
        controls.app_template_color_panel.hide();

        controls.app_scene_category_list_panel.hide();
        controls.app_scene_preview_image_panel.hide();
    }

    function showSceneDetailPanel() {
        controls.app_scene_list_panel.hide();
        controls.app_template_list_panel.hide();
        controls.app_scene_detail_panel.show();
        controls.app_template_color_panel.hide();

        controls.app_scene_category_list_panel.hide();
        controls.app_scene_preview_image_panel.hide();
    }

    function showColorDetialPanel() {
        controls.app_scene_list_panel.hide();
        controls.app_template_list_panel.hide();
        controls.app_scene_detail_panel.hide();

        controls.app_template_color_panel.show();

        controls.app_scene_category_list_panel.hide();
        controls.app_scene_preview_image_panel.hide();
    }

    function showCategorySetPanel() {
        controls.app_scene_list_panel.hide();
        controls.app_template_list_panel.hide();
        controls.app_scene_detail_panel.hide();

        controls.app_template_color_panel.hide();

        controls.app_scene_category_list_panel.show();
        controls.app_scene_preview_image_panel.hide();
    }

    function showAppScenePreviewImagePanel() {
        controls.app_scene_list_panel.hide();
        controls.app_template_list_panel.hide();
        controls.app_scene_detail_panel.hide();

        controls.app_template_color_panel.hide();

        controls.app_scene_category_list_panel.hide();
        controls.app_scene_preview_image_panel.show();
    }

    function initTagList(data) {
        if (data) {
            data = data.split('|');
        } else {
            data = [];
        }

        console.log(data);

        ajaxUtil.doAjaxGet(urls.tag_query, {page: 1, limit: 1000}).done(function (ret) {
            if (ret.status == 0) {
                $('#example-multiple-selected').empty();

                for (var i = 0; i < ret.data.rows.length; i++) {
                    var flag = false;

                    for (var j = 0; j < data.length; j++) {
                        if (data[j] == ret.data.rows[i].val) {
                            $('#example-multiple-selected').append('<option selected value="' + ret.data.rows[i].val + '">' + ret.data.rows[i].val + '</option>')
                            flag = true;
                            break;
                        }
                    }

                    if (flag == false) {
                        $('#example-multiple-selected').append('<option value="' + ret.data.rows[i].val + '">' + ret.data.rows[i].val + '</option>')
                    }
                }

                $('#example-multiple-selected').multiselect('rebuild');
            }
        })
    }

    function initTreeList(data) {
        var def = $.Deferred();
        if (data) {
            data = JSON.parse(data);
        } else {
            data = [];
        }

        ajaxUtil.doAjaxGet(urls.app_template_category_query, null).done(function (ret) {
            if (ret.status == 0) {
                var nodes = ret.data;

                for (var i = 0; i < nodes.length; i++) {
                    nodes[i].isParent = true;
                    nodes[i].name = nodes[i].val;

                    for (var j = 0; j < data.length; j++) {
                        if (data[j].val === nodes[i].val) {
                            nodes[i].checked = true;
                        }
                    }
                }

                nodes = commonUtil.arrayToTree(nodes);

                console.log(nodes);

                $.fn.zTree.init($("#app_template_menu_tree"), setting, nodes);
            }

            def.resolve();
        });

        return def.promise();
    }

    function colorRGB2Hex(color) {
        console.log(color);
        var rgb = color.split(',');
        var r = parseInt(rgb[0].split('(')[1]);
        var g = parseInt(rgb[1]);
        var b = parseInt(rgb[2].split(')')[0]);

        return {r: r, g: g, b: b};
    }

    function genSceneDetailDom(data) {
        return '    <tr>' +
            '        <td>' + data.type + '</td>' +
            '        <td>' + (data.position || "-") + '</td>' +
            '        <td>' + (data.size || "-") + '</td>' +
            '        <td>' + (data.name || data.color) + '</td>' +
            '        <td>-</td>' +
            '    </tr>';
    }

    function bindEvent() {
        controls.app_scene_category_list_panel.find('button:eq(0)').bind('click', function () {
            showTemplateListPanel();
        });
        controls.app_scene_category_list_panel.find('button:eq(1)').bind('click', function () {
            resetInputSceneCategory();
            G_MODIFY_CATEGORY_SCENE = false;
            controls.app_scene_category_detail_panel.modal('show');
        });

        controls.app_scene_category_detail_panel.find('button:eq(-2)').bind('click', function () {
            var args = {};

            var val = $.trim(controls.app_scene_category_detail_panel.find('input[type=text]:eq(0)').val());
            if (!val) return commonUtil.toast('场景分类名称不能为空');
            args.val = val;
            args.template_id = G_CURRENT_DATA_TEMPLATE.id;

            if (G_MODIFY_CATEGORY_SCENE) {
                args.id = G_CURRENT_DATA_CATEGORY_SCENE.id;
            }

            ajaxUtil.doAjaxPost(urls.save, args).done(function (ret) {
                if (ret.status == 0) {
                    controls.app_scene_category_detail_panel.modal('hide');
                    loadModelDataSceneCategory({template_id: G_CURRENT_DATA_TEMPLATE.id});
                } else {
                    commonUtil.toast(ret.msg);
                }
            });


        });

        $("#app_scene_category_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));

                G_MODIFY_CATEGORY_SCENE = true;
                G_CURRENT_DATA_CATEGORY_SCENE = data;

                resetInputSceneCategory();
                controls.app_scene_category_detail_panel.modal('show');

                controls.app_scene_category_detail_panel.find('input[type=text]:eq(0)').val(data.val);
            }
        }, '.resource-modify');

        // 点击删除
        $("#app_scene_category_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));
                bootbox.confirm({
                    title: "温馨提示",
                    message: "确认删除？",
                    buttons: {
                        cancel: {
                            label: '<i class="fa fa-times"></i> 取消'
                        },
                        confirm: {
                            label: '<i class="fa fa-check"></i> 确认'
                        }
                    },
                    callback: function (result) {
                        if (result) {
                            var args = {};
                            args.id = data.id;
                            ajaxUtil.doAjaxGet(urls.delete, args).done(function (ret) {
                                if (ret.status == 0) {
                                    loadModelDataSceneCategory({template_id: G_CURRENT_DATA_TEMPLATE.id});
                                } else {
                                    commonUtil.toast(ret.msg);
                                }

                            });
                        }
                    }
                });
            }
        }, '.resource-delete');

        // 点击新增模板
        controls.app_template_list_panel.find('button:eq(0)').bind('click', function () {
            resetInputTemplateData();
            G_MODIFY_TEMPLATE = false;
            controls.app_template_detail_panel.modal('show');
            initTreeList();
            initTagList();
        });

        // 模板查询
        controls.app_template_list_panel.find('button:eq(1)').bind('click', function () {
            refreshTemplateData();
        });

        // 模板保存
        controls.app_template_detail_panel.find('button:eq(-2)').bind('click', function () {
            var args = {};

            var result = $.trim(controls.template_style_edit.find('input:eq(0)').val());
            if (result && G_TEMPLATE_STYLE_IMAGE_URL) {
                controls.template_style_edit.find('button:eq(1)').trigger('click');
            }

            var title = $.trim(controls.app_template_detail_panel.find('input[type=text]:eq(0)').val());
            if (!title) return commonUtil.toast('标题不能为空');
            args.title = title;

            var doc_id = $.trim(controls.app_template_detail_panel.find('input[type=text]:eq(1)').val());
            args.doc_id = doc_id;

            var categories = [];
            var zTree = $.fn.zTree.getZTreeObj("app_template_menu_tree");
            var checkedNodes = zTree.getCheckedNodes(true);

            //版权
            // args.has_copyright  = controls.copyright_select.val();
            args.tool_type = controls.template_tool_type.val();

            args.scene_move_tag = controls.scene_preset_lock.val();

            $.each(checkedNodes, function (i, nodesObj) {
                var temp = {};
                temp.val = nodesObj.name;
                temp.level = nodesObj.level;

                categories.push(temp);
            });

            if (categories.length <= 0) return commonUtil.toast('模板分类不能为空');
            args.categories = JSON.stringify(categories);

            var tags = [];
            $('#example-multiple-selected option:selected').each(function () {
                tags.push($(this).val());
            });

            if (tags.length <= 0) return commonUtil.toast('模板标签不能为空');

            console.log(tags);
            args.tags = tags.join('|');

            args.des = $.trim(controls.app_template_detail_panel.find('textarea:eq(0)').val());
            if (!args.des) return commonUtil.toast('模板说明不能为空');

            args.intro = $.trim(controls.app_template_detail_panel.find('textarea:eq(1)').val());
            if (!args.intro) return commonUtil.toast('特色说明不能为空');

            args.sub_title = $.trim(controls.app_template_detail_panel.find('textarea:eq(2)').val());
            if (!args.sub_title) return commonUtil.toast('模板banner副标题不能为空');

            if (!G_TEMPLATE_BANNER_URL) return commonUtil.toast('请上传模板banner图片');
            args.banner_url = G_TEMPLATE_BANNER_URL;

            if (!G_TEMPLATE_IMAGE_URL) return commonUtil.toast('请上传模板缩略图片');
            args.preview_url = G_TEMPLATE_IMAGE_URL;

            if (!G_TEMPLATE_VIDEO_URL) return commonUtil.toast('请上传模板演示视频');
            args.video_url = G_TEMPLATE_VIDEO_URL;

            var styles = [];
            controls.app_template_detail_panel.find('.style-name').each(function () {
                styles.push({name: $(this).text(), id: $(this).attr('sid'), simage: $(this).attr('simage')});
            });

            if (styles.length <= 0) {
                styles.push({name: 'default', id: new Date().getTime(), simage: ''});
            }

            args.styles = JSON.stringify(styles);

            if (G_MODIFY_TEMPLATE) {
                args.id = G_CURRENT_DATA_TEMPLATE.id;
            }


            ajaxUtil.doAjaxPost(urls.template_save, args).done(function (ret) {
                if (ret.status == 0) {
                    controls.app_template_detail_panel.modal('hide');
                    refreshTemplateData();


                } else {
                    commonUtil.toast(ret.msg);
                }
            });


        });

        controls.app_template_color_panel.find('button:eq(0)').bind('click', function () {
            showTemplateListPanel();

        });

        controls.app_template_color_panel.find('button:eq(1)').bind('click', function () {
            appendRow(G_TEMPLATE_COLORITEMS)
        });

        controls.app_template_color_panel.find('button:eq(2)').bind('click', function () {
            var colors = [];
            controls.app_template_color_panel.find('tbody:eq(0)').find('tr').each(function () {
                var color = [];

                $(this).find('td').each(function () {
                    if ($(this).attr('tname')) {
                        var value = colorRGB2Hex($(this).find('input:eq(0)').css('background-color'));
                        console.log(value);
                        color.push({name: $(this).attr('tname'), color: value.r + ',' + value.g + ',' + value.b})
                    }
                });

                colors.push(color);
            });


            ajaxUtil.doAjaxPost(urls.template_save, {
                id: G_CURRENT_DATA_TEMPLATE.id,
                color: JSON.stringify(colors)
            }).done((function (ret) {
                if (ret.status == 0) {
                    showTemplateListPanel();
                    refreshTemplateData()
                }
            }))
        });

        // 模板修改
        $("#app_template_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));

                G_MODIFY_TEMPLATE = true;
                G_CURRENT_DATA_TEMPLATE = data;

                resetInputTemplateData();
                controls.app_template_detail_panel.modal('show');

                controls.app_template_detail_panel.find('input[type=text]:eq(0)').val(data.title);
                controls.app_template_detail_panel.find('input[type=text]:eq(1)').val(data.doc_id);
                initTreeList(data.categories);
                initTagList(data.tags);

                controls.app_template_detail_panel.find('.template-detail:eq(0)').text(data.sence_count);
                controls.app_template_detail_panel.find('.template-detail:eq(1)').text(data.export_count);
                controls.app_template_detail_panel.find('.template-detail:eq(2)').text(data.has_video == 0 ? "否" : "是");
                controls.app_template_detail_panel.find('.template-detail:eq(3)').text(data.during);
                controls.app_template_detail_panel.find('.template-detail:eq(4)').text(data.favorite_count);

                controls.app_template_detail_panel.find('textarea:eq(0)').val(data.des);
                controls.app_template_detail_panel.find('textarea:eq(1)').val(data.intro);
                controls.app_template_detail_panel.find('textarea:eq(2)').val(data.sub_title);

                //修改时选中has_copyright
                // controls.copyright_select.val(data.has_copyright);
                // controls.copyright_select.trigger('change');

                controls.template_tool_type.val(data.tool_type);
                controls.scene_preset_lock.val(data.scene_move_tag);
                controls.template_tool_type.trigger('change');
                controls.scene_preset_lock.trigger('changer');

                if (data.banner_url) {
                    G_TEMPLATE_BANNER_URL = data.banner_url;
                }
                if (data.preview_url) {
                    G_TEMPLATE_IMAGE_URL = data.preview_url;
                }

                if (data.video_url) {
                    G_TEMPLATE_VIDEO_URL = data.video_url;
                }

                var styles = JSON.parse(data.styles || '[]');

                for (var i = 0; i < styles.length; i++) {
                    var _dom =
                        '    <tr>' +
                        '        <td class="style-name" simage="' + styles[i].simage + '" sid="' + styles[i].id + '">' + styles[i].name + '</td>' +
                        '<td><img style="width: 50px;height: 80px;" src="' + styles[i].simage + '"/></td>' +
                        '        <td ><span class="style-edit">编辑</span>&nbsp;&nbsp;<span class="style-delete">删除</span></td>' +
                        '    </tr>';
                    controls.app_template_detail_panel.find('tbody:eq(0)').append(_dom);
                }

                showStyleList();

            }
        }, '.resource-modify');

        // 颜色管理展开颜色面板
        $("#app_template_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));

                G_CURRENT_DATA_TEMPLATE = data;

                showColorDetialPanel();
                G_CURRENT_COLOR_DATA = null;
                G_TEMPLATE_COLORITEMS = [];
                G_TEMPLATE_COLORS = JSON.parse(data.color || '[[]]');


                ajaxUtil.doAjaxGet(urls.template_color, {template_id: G_CURRENT_DATA_TEMPLATE.id}).done(function (ret) {
                    if (ret.status == 0) {
                        G_CURRENT_COLOR_DATA = ret.data;

                        G_TEMPLATE_COLORITEMS = ret.data.map(function (item) {
                            return item.name;
                        });

                        controls.app_template_color_panel.find('thead:eq(0)').empty();
                        controls.app_template_color_panel.find('thead:eq(0)').append(genColorHead(G_TEMPLATE_COLORITEMS));

                        controls.app_template_color_panel.find('tbody:eq(0)').empty();
                        genColorBody(G_TEMPLATE_COLORS);
                    } else {
                        commonUtil.toast(ret.msg);
                    }

                })
            }
        }, '.resource-color');

        function genColorHead(items) {
            var _dom = '<tr>';
            for (var i = 0; i < items.length; i++) {
                _dom += '<th>' + items[i] + '</th>';
            }

            _dom += '<td>操作</td>'

            return _dom += '</tr>'
        }

        function appendRow(data) {
            var _dom = $('<tr></tr>');

            for (var i = 0; i < data.length; i++) {
                var input = document.createElement('INPUT');
                var picker = new jscolor(input)
                picker.fromRGB(0, 0, 0)
                var $td = $('<td style="width: 50px;" tname="' + data[i] + '"></td>')
                $td.append(input);
                _dom.append($td);
            }
            _dom.append('<td class="color-item-delete">删除</td>');

            controls.app_template_color_panel.find('tbody:eq(0)').append(_dom);
        }

        function genColorBody(colors) {
            console.log(colors);
            if (colors.length > 0) {
                for (var i = 0; i < colors.length; i++) {

                    var _dom = $('<tr></tr>');
                    var colorArr = colors[i];

                    for (var k = 0; k < G_TEMPLATE_COLORITEMS.length; k++) {
                        console.log(G_TEMPLATE_COLORITEMS[k]);
                        var flag = false;

                        for (var j = 0; j < colorArr.length; j++) {
                            var colorItem = colorArr[j];

                            if (G_TEMPLATE_COLORITEMS[k] == colorItem.name) {
                                var input = document.createElement('INPUT');
                                var picker = new jscolor(input);
                                var colorVal = colorItem.color.split(',');
                                console.log(colorVal);
                                picker.fromRGB(parseInt(colorVal[0]), parseInt(colorVal[1]), parseInt(colorVal[2]));
                                var $td = $('<td style="width: 50px;" tname="' + colorItem.name + '"></td>')
                                $td.append(input);
                                _dom.append($td);

                                flag = true;
                                break;
                            }
                        }

                        console.log('flag', flag);

                        if (!flag) {
                            var input = document.createElement('INPUT');
                            var picker = new jscolor(input)
                            picker.fromRGB(0, 0, 0)
                            var $td = $('<td style="width: 50px;"  tname="' + G_TEMPLATE_COLORITEMS[k] + '"></td>')
                            $td.append(input);
                            _dom.append($td);
                        }
                    }

                    _dom.append('<td class="color-item-delete">删除</td>');

                    controls.app_template_color_panel.find('tbody:eq(0)').append(_dom);


                }
            }
        }

        controls.app_template_color_panel.find('tbody:eq(0)').on({
            'click': function () {
                $(this).parent().remove();
            }
        }, '.color-item-delete');


        // 点击进入场景列表
        $("#app_template_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));
                G_TIMER = true;
                G_CURRENT_DATA_TEMPLATE = data;
                showSceneListPanel();

                refreshSceneData();
                refreshPresetData();
            }
        }, '.resource-scene');

        // 点击删除
        $("#app_template_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));


                bootbox.confirm({
                    title: "温馨提示",
                    message: "确认删除？",
                    buttons: {
                        cancel: {
                            label: '<i class="fa fa-times"></i> 取消'
                        },
                        confirm: {
                            label: '<i class="fa fa-check"></i> 确认'
                        }
                    },
                    callback: function (result) {
                        if (result) {
                            var args = {};
                            args.id = data.id;
                            ajaxUtil.doAjaxGet(urls.template_del, args).done(function (ret) {
                                if (ret.status == 0) {
                                    refreshTemplateData();
                                } else {
                                    commonUtil.toast(ret.msg);
                                }

                            });
                        }
                    }
                });
            }
        }, '.resource-delete');

        // 点击删除
        $("#app_template_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));
                var msg = '确认下架？';
                if (!data.is_publish) {
                    msg = '确认上架？';
                }

                bootbox.confirm({
                    title: "温馨提示",
                    message: msg,
                    buttons: {
                        cancel: {
                            label: '<i class="fa fa-times"></i> 取消'
                        },
                        confirm: {
                            label: '<i class="fa fa-check"></i> 确认'
                        }
                    },
                    callback: function (result) {
                        if (result) {
                            var args = {};
                            args.id = data.id;
                            args.is_publish = data.is_publish ? 0 : 1;
                            ajaxUtil.doAjaxGet(urls.template_publish, args).done(function (ret) {
                                if (ret.status == 0) {
                                    refreshTemplateData();
                                } else {
                                    commonUtil.toast(ret.msg);
                                }

                            });
                        }
                    }
                });
            }
        }, '.resource-publish');

        $("#app_template_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));
                console.log(data);

                G_CURRENT_DATA_TEMPLATE = data;
                showCategorySetPanel();
                loadModelDataSceneCategory({template_id: data.id})
            }
        }, '.resource-scene-category');

        // 点击删除
        $("#app_scene_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));


                bootbox.confirm({
                    title: "温馨提示",
                    message: "确认删除？",
                    buttons: {
                        cancel: {
                            label: '<i class="fa fa-times"></i> 取消'
                        },
                        confirm: {
                            label: '<i class="fa fa-check"></i> 确认'
                        }
                    },
                    callback: function (result) {
                        if (result) {
                            var args = {};
                            args.id = data.id;
                            args.template_id = G_CURRENT_DATA_TEMPLATE.id;
                            ajaxUtil.doAjaxGet(urls.scene_del, args).done(function (ret) {
                                if (ret.status == 0) {
                                    refreshSceneData();
                                } else {
                                    commonUtil.toast(ret.msg);
                                }

                            });
                        }
                    }
                });
            }
        }, '.resource-delete');


        // 点击设重新置场景预览图
        $("#app_scene_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));
                data.style = JSON.parse(data.style);

                G_CURRENT_DATA_SCENE = data;

                var extra = null;
                if (data.style.length <= 0) {
                    return commonUtil.toast('没有可用模板，请上传')
                }
                extra = data.style[0].extra;

                console.log(data);
                showAppScenePreviewImagePanel();

                G_SCENE_PREVIEW_IMAGE = null;

                controls.app_scene_preview_image_panel_node.find('img:eq(0)').attr('src', G_CURRENT_DATA_SCENE.img_url);

                var resolution = extra.custom.resolution;

                canvas = window._canvas = new fabric.Canvas('c');
                polygons = {};

                // 舞台渲染
                var images = extra.custom.image;
                if (images) {
                    let p = [];
                    for (var i = 0; i < images.length; i++) {
                        var item = images[i];
                        var pp = [];
                        item.position = Array.isArray(item.position) ? item.position : item.position.split(',');
                        item.size = Array.isArray(item.size) ? item.size : item.size.split(',');
                        this.state = {
                            stageWidth: 960,
                            stageHeight: 540,
                        };

                        this.stage = {
                            width: 1920,
                            height: 1080,
                        }

                        var left = `${((item.position[0] * this.state.stageWidth) / parseInt(resolution ? resolution.split(',')[0] : this.stage.width))}`;
                        var top = `${(item.position[1] * this.state.stageHeight) / parseInt(resolution ? resolution.split(',')[1] : this.stage.height)}`;
                        var width = `${(item.size[0] * this.state.stageWidth) / parseInt(resolution ? resolution.split(',')[0] : this.stage.width)}`;
                        var height = `${(item.size[1] * this.state.stageHeight) / parseInt(resolution ? resolution.split(',')[1] : this.stage.height)}`;

                        pp.push({x: parseInt(left), y: parseInt(top)});
                        pp.push({x: parseInt(left) + parseInt(width), y: parseInt(top)});
                        pp.push({x: parseInt(left) + parseInt(width), y: parseInt(top) + parseInt(height)});
                        pp.push({x: parseInt(left), y: parseInt(top) + parseInt(height)});

                        p.push(pp)
                    }

                    G_POINTS_ORI.image = p;
                }

                var videos = extra.custom.video;
                if (videos) {
                    let p = [];
                    for (var i = 0; i < videos.length; i++) {
                        var item = videos[i];
                        var pp = [];
                        item.position = Array.isArray(item.position) ? item.position : item.position.split(',');
                        item.size = Array.isArray(item.size) ? item.size : item.size.split(',');
                        this.state = {
                            stageWidth: 960,
                            stageHeight: 540,
                        };

                        this.stage = {
                            width: 1920,
                            height: 1080,
                        }

                        var left = `${((item.position[0] * this.state.stageWidth) / parseInt(resolution ? resolution.split(',')[0] : this.stage.width))}`;
                        var top = `${(item.position[1] * this.state.stageHeight) / parseInt(resolution ? resolution.split(',')[1] : this.stage.height)}`;
                        var width = `${(item.size[0] * this.state.stageWidth) / parseInt(resolution ? resolution.split(',')[0] : this.stage.width)}`;
                        var height = `${(item.size[1] * this.state.stageHeight) / parseInt(resolution ? resolution.split(',')[1] : this.stage.height)}`;

                        pp.push({x: parseInt(left), y: parseInt(top)});
                        pp.push({x: parseInt(left) + parseInt(width), y: parseInt(top)});
                        pp.push({x: parseInt(left) + parseInt(width), y: parseInt(top) + parseInt(height)});
                        pp.push({x: parseInt(left), y: parseInt(top) + parseInt(height)});

                        p.push(pp);
                    }

                    G_POINTS_ORI.video = p;
                }

                var texts = extra.custom.text;
                if (texts) {
                    let p = [];
                    for (var i = 0; i < texts.length; i++) {
                        var item = texts[i];
                        var pp = [];
                        item.position = Array.isArray(item.position) ? item.position : item.position.split(',');
                        item.size = Array.isArray(item.size) ? item.size : item.size.split(',');
                        this.state = {
                            stageWidth: 960,
                            stageHeight: 540,
                        };

                        this.stage = {
                            width: 1920,
                            height: 1080,
                        }

                        var left = `${((item.position[0] * this.state.stageWidth) / parseInt(resolution ? resolution.split(',')[0] : this.stage.width))}`;
                        var top = `${(item.position[1] * this.state.stageHeight) / parseInt(resolution ? resolution.split(',')[1] : this.stage.height)}`;
                        var width = `${(item.size[0] * this.state.stageWidth) / parseInt(resolution ? resolution.split(',')[0] : this.stage.width)}`;
                        var height = `${(item.size[1] * this.state.stageHeight) / parseInt(resolution ? resolution.split(',')[1] : this.stage.height)}`;

                        pp.push({x: parseInt(left), y: parseInt(top)});
                        pp.push({x: parseInt(left) + parseInt(width), y: parseInt(top)});
                        pp.push({x: parseInt(left) + parseInt(width), y: parseInt(top) + parseInt(height)});
                        pp.push({x: parseInt(left), y: parseInt(top) + parseInt(height)});

                        p.push(pp);
                    }

                    G_POINTS_ORI.text = p;
                }


                if (data.points) {
                    G_POINTS = JSON.parse(data.points);
                } else {
                    G_POINTS = JSON.parse(JSON.stringify(G_POINTS_ORI));
                }

                console.log('G_POINTS', G_POINTS);

                canvas.clear();

                addPolygon();
                addControlPoints();

                canvas.on({
                    'object:moving': updateControls,
                    'object:scaling': updateControls,
                    'object:resizing': updateControls,
                    'object:rotating': updateControls,
                    'object:skewing': updateControls,
                    'mouse:down': function (options) {
                        console.log(options);
                        console.log('mouse:down')
                    }
                });
            }
        }, '.resource-preview-set');

        $('#app_scene_preview_image_panel').find('button:eq(0)').bind('click', function () {
            showSceneListPanel();

            canvas.clear();
            canvas.dispose();
            G_POINTS = {};
            G_POINTS_ORI = {};
            polygons = {};
        });

        $('#app_scene_preview_image_panel').find('button:eq(1)').bind('click', function () {

            var data = G_CURRENT_DATA_SCENE;

            for (var si = 0; si < data.style.length; si++) {
                var dataStyle = data.style[si];
                if (dataStyle.extra.custom.image) {
                    for (var ii = 0; ii < dataStyle.extra.custom.image.length; ii++) {
                        var from = G_POINTS_ORI.image[ii];
                        var originalPos = [[from[0].x,from[0].y],[from[3].x,from[3].y],[from[1].x,from[1].y],[from[2].x,from[2].y]];

                        var to = G_POINTS.image[ii];
                        var targetPos = [[to[0].x,to[0].y],[to[3].x,to[3].y],[to[1].x,to[1].y],[to[2].x,to[2].y]];

                        var from_x = (function () {
                            var k, len, results;
                            results = [];
                            for (k = 0, len = originalPos.length; k < len; k++) {
                                var p = originalPos[k];
                                results.push({
                                    x: p[0] - originalPos[0][0],
                                    y: p[1] - originalPos[0][1]
                                });
                            }

                            return results;
                        })();
                        var to_x = (function () {
                            var k, len, results;
                            results = [];
                            for (k = 0, len = targetPos.length; k < len; k++) {
                                var p = targetPos[k];
                                results.push({
                                    x: p[0] - originalPos[0][0],
                                    y: p[1] - originalPos[0][1]
                                });
                            }

                            return results;
                        })();

                        var H = getTransform(from_x, to_x);

                        dataStyle.extra.custom.image[ii].transform = `matrix3d(${((function () {
                            var k, results;
                            results = [];
                            for (var i = k = 0; k < 4; i = ++k) {
                                results.push((function () {
                                    var l, results1;
                                    results1 = [];
                                    for (var j = l = 0; l < 4; j = ++l) {
                                        results1.push(H[j][i].toFixed(20));
                                    }

                                    return results1;
                                })());
                            }

                            return results;
                        })()).join(',')})`;
                        dataStyle.extra.custom.image[ii].transformOrigin = '0 0';

                        dataStyle.extra.custom.image[ii].position = dataStyle.extra.custom.image[ii].position.join(',');
                        dataStyle.extra.custom.image[ii].size = dataStyle.extra.custom.image[ii].size.join(',');
                    }
                }
            }

            for (var si = 0; si < data.style.length; si++) {
                var dataStyle = data.style[si];
                if (dataStyle.extra.custom.video) {
                    for (var ii = 0; ii < dataStyle.extra.custom.video.length; ii++) {
                        var from = G_POINTS_ORI.video[ii];
                        var originalPos = [[from[0].x,from[0].y],[from[3].x,from[3].y],[from[1].x,from[1].y],[from[2].x,from[2].y]];

                        var to = G_POINTS.video[ii];
                        var targetPos = [[to[0].x,to[0].y],[to[3].x,to[3].y],[to[1].x,to[1].y],[to[2].x,to[2].y]];

                        var from_x = (function () {
                            var k, len, results;
                            results = [];
                            for (k = 0, len = originalPos.length; k < len; k++) {
                                var p = originalPos[k];
                                results.push({
                                    x: p[0] - originalPos[0][0],
                                    y: p[1] - originalPos[0][1]
                                });
                            }

                            return results;
                        })();
                        var to_x = (function () {
                            var k, len, results;
                            results = [];
                            for (k = 0, len = targetPos.length; k < len; k++) {
                                var p = targetPos[k];
                                results.push({
                                    x: p[0] - originalPos[0][0],
                                    y: p[1] - originalPos[0][1]
                                });
                            }

                            return results;
                        })();

                        var H = getTransform(from_x, to_x);

                        dataStyle.extra.custom.video[ii].transform = `matrix3d(${((function () {
                            var k, results;
                            results = [];
                            for (var i = k = 0; k < 4; i = ++k) {
                                results.push((function () {
                                    var l, results1;
                                    results1 = [];
                                    for (var j = l = 0; l < 4; j = ++l) {
                                        results1.push(H[j][i].toFixed(20));
                                    }

                                    return results1;
                                })());
                            }

                            return results;
                        })()).join(',')})`;
                        dataStyle.extra.custom.video[ii].transformOrigin = '0 0';

                        dataStyle.extra.custom.video[ii].position = dataStyle.extra.custom.video[ii].position.join(',');
                        dataStyle.extra.custom.video[ii].size = dataStyle.extra.custom.video[ii].size.join(',');

                    }
                }
            }

            for (var si = 0; si < data.style.length; si++) {
                var dataStyle = data.style[si];
                if (dataStyle.extra.custom.text) {
                    for (var ii = 0; ii < dataStyle.extra.custom.text.length; ii++) {
                        var from = G_POINTS_ORI.text[ii];
                        var originalPos = [[from[0].x,from[0].y],[from[3].x,from[3].y],[from[1].x,from[1].y],[from[2].x,from[2].y]];

                        var to = G_POINTS.text[ii];
                        var targetPos = [[to[0].x,to[0].y],[to[3].x,to[3].y],[to[1].x,to[1].y],[to[2].x,to[2].y]];

                        var from_x = (function () {
                            var k, len, results;
                            results = [];
                            for (k = 0, len = originalPos.length; k < len; k++) {
                                var p = originalPos[k];
                                results.push({
                                    x: p[0] - originalPos[0][0],
                                    y: p[1] - originalPos[0][1]
                                });
                            }

                            return results;
                        })();
                        var to_x = (function () {
                            var k, len, results;
                            results = [];
                            for (k = 0, len = targetPos.length; k < len; k++) {
                                var p = targetPos[k];
                                results.push({
                                    x: p[0] - originalPos[0][0],
                                    y: p[1] - originalPos[0][1]
                                });
                            }

                            return results;
                        })();
                        var H = getTransform(from_x, to_x);
                        dataStyle.extra.custom.text[ii].transform = `matrix3d(${((function () {
                            var k, results;
                            results = [];
                            for (var i = k = 0; k < 4; i = ++k) {
                                results.push((function () {
                                    var l, results1;
                                    results1 = [];
                                    for (var j = l = 0; l < 4; j = ++l) {
                                        results1.push(H[j][i].toFixed(20));
                                    }

                                    return results1;
                                })());
                            }

                            return results;
                        })()).join(',')})`;
                        dataStyle.extra.custom.text[ii].transformOrigin = '0 0';

                        dataStyle.extra.custom.text[ii].position = dataStyle.extra.custom.text[ii].position.join(',');
                        dataStyle.extra.custom.text[ii].size = dataStyle.extra.custom.text[ii].size.join(',');
                    }
                }
            }

            console.log(data);

            var args = {};
            args.style = JSON.stringify(data.style);

            args.points = JSON.stringify(G_POINTS);
            args.id = data.id;
            if (G_SCENE_PREVIEW_IMAGE) {
                args.img_url = G_SCENE_PREVIEW_IMAGE;
            }

            ajaxUtil.doAjaxPost(urls.scene_save_pure, args).done(function (ret) {
                if (ret.status == 0) {
                    canvas.clear();
                    canvas.dispose();
                    G_POINTS = {};
                    G_POINTS_ORI = {};
                    polygons = {};
                    showSceneListPanel();
                    refreshSceneData()
                } else {
                    commonUtil.toast(ret.msg);
                }
            });

            console.log(data);
        });

        $("#app_scene_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));
                var args = {};
                args.id = data.id;
                ajaxUtil.doAjaxGet(urls.scene_render, args).done(function (ret) {
                    if (ret.status == 0) {
                        commonUtil.toast('成功添渲染队列')
                        refreshSceneData();
                    } else {
                        commonUtil.toast(ret.msg);
                    }

                });
            }
        }, '.resource-status');

        $("#app_scene_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));
                G_CURRENT_RENDER_ITEM = data;
                controls.app_template_render_success.find('a:eq(0)').attr('href', data.ori_video_url);
                controls.app_template_render_success.find('a:eq(1)').attr('href', data.video_url);
                controls.app_template_render_success.find('#batchId').text(data.task_id);
                // controls.app_template_render_success.find('p:eq(1)').text(data.task_obj);

                controls.app_template_render_success.modal('show');
            }
        }, '.resource-render-success');

        controls.app_template_render_success.find('button:eq(-2)').bind('click', function () {
            controls.app_template_render_success.modal('hide');
            var data = G_CURRENT_RENDER_ITEM;
            var args = {};
            args.id = data.id;
            ajaxUtil.doAjaxGet(urls.scene_render, args).done(function (ret) {
                if (ret.status == 0) {
                    commonUtil.toast('成功添渲染队列')
                    refreshSceneData();
                } else {
                    commonUtil.toast(ret.msg);
                }

            });
        })

        // 场景修改
        $("#app_scene_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));

                G_MODIFY_SCENE = true;
                G_CURRENT_DATA_SCENE = data;

                resetInputSceneData();
                showSceneDetailPanel();

                controls.app_scene_detail_panel.find('input[type=text]:eq(0)').val(data.title);

                $('#scene_min_time_input').val(data.min_time||'');
                controls.app_scene_detail_panel.find('select:eq(2)').val(data.type);

                // controls.app_scene_detail_panel.find('select:eq(0)').val(data.category);
                controls.app_scene_detail_panel.find('input[type=text]:eq(1)').val(data.category);

                G_SCENE_MUSIC = JSON.parse(data.music) || [];

                var style = JSON.parse(data.style || '[]');
                var styles = JSON.parse(G_CURRENT_DATA_TEMPLATE.styles || '[]');
                if (styles.length <= 0) {
                    if (style.length == 1 && style[0].extra) {
                        controls.app_scene_detail_panel.find('.style-div').attr('upload_info', encodeURIComponent(JSON.stringify(style[0].extra)));
                        $('#template_store_doc_id').val(style[0].extra.doc_id || '');

                        let upload_info = style[0].extra;
                        console.log(upload_info);
                        if (upload_info != '{}') {

                            controls.app_scene_detail_panel.find('tbody:eq(0)').empty();

                            upload_info.custom.text && upload_info.custom.text.forEach(function (item) {
                                item.type = "文本";
                                controls.app_scene_detail_panel.find('tbody:eq(0)').append(genSceneDetailDom(item))
                            });
                            upload_info.custom.color && upload_info.custom.color.forEach(function (item) {
                                item.type = "颜色";
                                controls.app_scene_detail_panel.find('tbody:eq(0)').append(genSceneDetailDom(item))
                            });
                            upload_info.custom.image && upload_info.custom.image.forEach(function (item) {
                                item.type = "图片";
                                controls.app_scene_detail_panel.find('tbody:eq(0)').append(genSceneDetailDom(item))
                            });
                            upload_info.custom.video && upload_info.custom.video.forEach(function (item) {
                                item.type = "视频";
                                controls.app_scene_detail_panel.find('tbody:eq(0)').append(genSceneDetailDom(item))
                            });

                            $('#template_store_position').text(upload_info.templateBase)
                        } else {
                            $('#template_store_position').text('')
                        }
                    }


                } else {
                    controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').find('option').each(function () {
                        for (var i = 0; i < style.length; i++) {
                            if (style[i].style_id == $(this).attr('value')) {
                                $(this).attr('upload_info', encodeURIComponent(JSON.stringify(style[i].extra)))

                            }
                        }
                    });

                    controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').trigger('change');
                }

                controls.app_scene_detail_panel.find('tbody:eq(1)').empty();
                if (styles.length <= 0) {
                    G_SCENE_MUSIC.forEach(function (item) {
                        controls.app_scene_detail_panel.find('tbody:eq(1)').append('<tr><td>' + item.name + '</td><td class="music-delete" mid="' + item.id + '">删除</td></tr>')
                    });
                } else {
                    var tempArr = G_SCENE_MUSIC && G_SCENE_MUSIC.filter(function (item) {
                        return item.style_id == controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').find('option:selected').val();
                    });

                    tempArr && tempArr.forEach(function (item) {
                        controls.app_scene_detail_panel.find('tbody:eq(1)').append('<tr><td>' + item.name + '</td><td class="music-delete" mid="' + item.id + '">删除</td></tr>')
                    });
                }


            }
        }, '.resource-modify');

        // 场景列表返回模板列表
        controls.app_scene_list_panel.find('button:eq(0)').bind('click', function () {
            showTemplateListPanel();
            refreshTemplateData();
            G_TIMER = false;
        });

        controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').on('change', function () {
            var upload_info = decodeURIComponent(controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').find('option:selected').attr('upload_info'));
            $('#template_store_doc_id').val('');
            $('#template_store_position').text('')
            console.log('upload_info', upload_info);
            controls.app_scene_detail_panel.find('tbody:eq(0)').empty();
            if (upload_info != '{}') {
                upload_info = JSON.parse(upload_info);

                console.log('upload_info', upload_info);

                controls.app_scene_detail_panel.find('tbody:eq(0)').empty();

                if (upload_info.custom) {
                    upload_info.custom.text && upload_info.custom.text.forEach(function (item) {
                        item.type = "文本";
                        controls.app_scene_detail_panel.find('tbody:eq(0)').append(genSceneDetailDom(item))
                    });
                    upload_info.custom.color && upload_info.custom.color.forEach(function (item) {
                        item.type = "颜色";
                        controls.app_scene_detail_panel.find('tbody:eq(0)').append(genSceneDetailDom(item))
                    });
                    upload_info.custom.image && upload_info.custom.image.forEach(function (item) {
                        item.type = "图片";
                        controls.app_scene_detail_panel.find('tbody:eq(0)').append(genSceneDetailDom(item))
                    });
                    upload_info.custom.video && upload_info.custom.video.forEach(function (item) {
                        item.type = "视频";
                        controls.app_scene_detail_panel.find('tbody:eq(0)').append(genSceneDetailDom(item))
                    });
                }

                $('#template_store_doc_id').val(upload_info.doc_id || '');

                $('#template_store_position').text(upload_info.templateBase)
            } else {
                $('#template_store_position').text('')
            }

            controls.app_scene_detail_panel.find('tbody:eq(1)').empty();
            let tempArr = G_SCENE_MUSIC && G_SCENE_MUSIC.filter(function (item) {
                return item.style_id == controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').find('option:selected').val();
            });

            tempArr && tempArr.forEach(function (item) {
                controls.app_scene_detail_panel.find('tbody:eq(1)').append('<tr><td>' + item.name + '</td><td class="music-delete" mid="' + item.id + '">删除</td></tr>')
            });
        });

        controls.input_template_music_upload.fileinput({
            language: 'zh', //设置语言
            uploadUrl: '/admin/file/upload-template-music', //上传的地址
            allowedFileExtensions: ['mp3'],//接收的文件后缀
            showUpload: false, //是否显示上传按钮
            showCaption: false,//是否显示标题,
            showRemove: false,
            uploadAsync: true,
            browseClass: "btn btn-primary", //按钮样式
        }).on("filebatchselected", function (event, files) {
            controls.input_template_music_upload.fileinput("upload");
        }).on("fileuploaded", function (event, data, previewId, index) {
            console.log(data);

            let ret = data.response;
            if (ret.status !== 0) return commonUtil.toast(ret.msg);

            let retData = ret.data;
            delete retData.admin_id;

            var styles = JSON.parse(G_CURRENT_DATA_TEMPLATE.styles || '[]');
            if (styles.length <= 0) {
                G_SCENE_MUSIC.push(retData);
            } else {
                retData.style_id = controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').find('option:selected').val();
                G_SCENE_MUSIC.push(retData);
            }

            controls.app_scene_detail_panel.find('tbody:eq(1)').empty();
            if (styles.length <= 0) {
                G_SCENE_MUSIC.forEach(function (item) {
                    controls.app_scene_detail_panel.find('tbody:eq(1)').append('<tr><td>' + item.name + '</td><td class="music-delete" mid="' + item.id + '">删除</td></tr>')
                });
            } else {
                var tempArr = G_SCENE_MUSIC.filter(function (item) {
                    return item.style_id == controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').find('option:selected').val();
                });

                tempArr.forEach(function (item) {
                    controls.app_scene_detail_panel.find('tbody:eq(1)').append('<tr><td>' + item.name + '</td><td class="music-delete" mid="' + item.id + '">删除</td></tr>')
                });
            }
        });

        controls.app_scene_detail_panel.find('tbody:eq(1)').on({
            'click': function () {
                var mid = $(this).attr('mid');
                controls.app_scene_detail_panel.find('tbody:eq(1)').empty();
                G_SCENE_MUSIC = G_SCENE_MUSIC.filter(function (item) {
                    return item.id != mid;
                });

                console.log(G_SCENE_MUSIC);

                var styles = JSON.parse(G_CURRENT_DATA_TEMPLATE.styles || '[]');
                if (styles.length <= 0) {
                    G_SCENE_MUSIC.forEach(function (item) {
                        controls.app_scene_detail_panel.find('tbody:eq(1)').append('<tr><td>' + item.name + '</td><td class="music-delete" mid="' + item.id + '">删除</td></tr>')
                    });
                } else {
                    var tempArr = G_SCENE_MUSIC.filter(function (item) {
                        return item.style_id == controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').find('option:selected').val();
                    });

                    tempArr.forEach(function (item) {
                        controls.app_scene_detail_panel.find('tbody:eq(1)').append('<tr><td>' + item.name + '</td><td class="music-delete" mid="' + item.id + '">删除</td></tr>')
                    });
                }
            }
        }, '.music-delete');

        controls.input_template_banner_upload.fileinput({
            language: 'zh', //设置语言
            uploadUrl: '/admin/file/upload-to-ali-oss', //上传的地址
            allowedFileExtensions: ['jpg', 'jpeg', 'png'],//接收的文件后缀
            showUpload: false, //是否显示上传按钮
            showCaption: false,//是否显示标题,
            showRemove: false,
            uploadAsync: true,
            maxFileCount: 10,
            fileActionSettings: {
                showRemove: false,
            },
            browseClass: "btn btn-primary", //按钮样式
        }).on("filebatchselected", function (event, files) {
            controls.input_template_banner_upload.fileinput("upload");
        }).on("fileuploaded", function (event, data, previewId, index) {
            console.log(data);
            var ret = data.response;
            if (ret.status != 0) {
                return commonUtil.toast(ret.msg);
            }
            G_TEMPLATE_BANNER_URL = ret.data.url;
        });


        controls.input_template_preset_image_upload.fileinput({
            language: 'zh', //设置语言
            uploadUrl: '/admin/file/upload-to-ali-oss', //上传的地址
            allowedFileExtensions: ['jpg', 'jpeg', 'png'],//接收的文件后缀
            showUpload: false, //是否显示上传按钮
            showCaption: false,//是否显示标题,
            showRemove: false,
            uploadAsync: true,
            maxFileCount: 10,
            fileActionSettings: {
                showRemove: false,
            },
            browseClass: "btn btn-primary", //按钮样式
        }).on("filebatchselected", function (event, files) {
            controls.input_template_preset_image_upload.fileinput("upload");
        }).on("fileuploaded", function (event, data, previewId, index) {
            console.log(data);
            var ret = data.response;
            if (ret.status != 0) {
                return commonUtil.toast(ret.msg);
            }
            PRESET_IMAGE_URL = ret.data.url;
        });
        controls.input_template_preset_video_upload.fileinput({
            language: 'zh', //设置语言
            uploadUrl: $('#upload_host').text(), //上传的地址
            allowedFileExtensions: ['mp4'],//接收的文件后缀
            showUpload: false, //是否显示上传按钮
            showCaption: false,//是否显示标题,
            showRemove: false,
            uploadAsync: true,
            browseClass: "btn btn-primary", //按钮样式
            uploadExtraData:function() {
                var dataObj = {};
                dataObj.key = 'user/publish/'+ new Date().getTime() + Math.floor(Math.random()*100000000)+'.mp4';
                dataObj.OSSAccessKeyId = G_UPLOAD_POLICY.OSSAccessKeyId;
                dataObj.host = G_UPLOAD_POLICY.host;
                dataObj.policy = G_UPLOAD_POLICY.policy;
                dataObj.signature = G_UPLOAD_POLICY.signature;
                dataObj.success_action_status = G_UPLOAD_POLICY.G_UPLOAD_POLICY;
                dataObj.callback = G_UPLOAD_POLICY.callback;
                dataObj.expire = G_UPLOAD_POLICY.expire;
                return dataObj;
            }
        }).on("filebatchselected", function (event, files) {
            controls.input_template_preset_video_upload.fileinput("upload");
        }).on("fileuploaded", function (event, data, previewId, index) {
            console.log(data);
            var ret = data.response;
            if (ret.status != 0) {
                return commonUtil.toast(ret.msg);
            }
            PRESET_VIDEO_URL = ret.data.url;
        });


        controls.input_template_color_svg_upload.fileinput({
            language: 'zh', //设置语言
            uploadUrl: '/admin/file/upload-to-ali-oss', //上传的地址
            allowedFileExtensions: ['svg'],//接收的文件后缀
            showUpload: false, //是否显示上传按钮
            showCaption: false,//是否显示标题,
            showRemove: false,
            uploadAsync: true,
            maxFileCount: 10,
            fileActionSettings: {
                showRemove: false,
            },
            browseClass: "btn btn-primary", //按钮样式
        }).on("filebatchselected", function (event, files) {
            controls.input_template_color_svg_upload.fileinput("upload");
        }).on("fileuploaded", function (event, data, previewId, index) {
            console.log(data);
            var ret = data.response;
            if (ret.status != 0) {
                return commonUtil.toast(ret.msg);
            }

            ajaxUtil.doAjaxGet(urls.template_set_svg, {
                color_svg_url: ret.data.url,
                id: G_CURRENT_DATA_TEMPLATE.id
            }).done(function (ret) {
                if (ret.status != 0) {
                    return commonUtil.toast(ret.msg);
                } else {
                    commonUtil.toast('添加成功')
                }
            });
        });

        controls.input_template_image_upload.fileinput({
            language: 'zh', //设置语言
            uploadUrl: '/admin/file/upload-to-ali-oss', //上传的地址
            allowedFileExtensions: ['jpg', 'jpeg', 'png'],//接收的文件后缀
            showUpload: false, //是否显示上传按钮
            showCaption: false,//是否显示标题,
            showRemove: false,
            uploadAsync: true,
            maxFileCount: 10,
            fileActionSettings: {
                showRemove: false,
            },
            browseClass: "btn btn-primary", //按钮样式
        }).on("filebatchselected", function (event, files) {
            controls.input_template_image_upload.fileinput("upload");
        }).on("fileuploaded", function (event, data, previewId, index) {
            console.log(data);
            var ret = data.response;
            if (ret.status != 0) {
                return commonUtil.toast(ret.msg);
            }
            G_TEMPLATE_IMAGE_URL = ret.data.url;
        });

        controls.input_scene_preview_image_upload.fileinput({
            language: 'zh', //设置语言
            uploadUrl: '/admin/file/upload-to-ali-oss', //上传的地址
            allowedFileExtensions: ['jpg', 'jpeg', 'png'],//接收的文件后缀
            showUpload: false, //是否显示上传按钮
            showCaption: false,//是否显示标题,
            showRemove: false,
            uploadAsync: true,
            maxFileCount: 10,
            fileActionSettings: {
                showRemove: false,
            },
            browseLabel: '点击重新上传预览图',
            browseClass: "btn btn-primary", //按钮样式
        }).on("filebatchselected", function (event, files) {
            controls.input_scene_preview_image_upload.fileinput("upload");
        }).on("fileuploaded", function (event, data, previewId, index) {
            console.log(data);
            var ret = data.response;
            if (ret.status != 0) {
                return commonUtil.toast(ret.msg);
            }
            G_SCENE_PREVIEW_IMAGE = ret.data.url;

            controls.app_scene_preview_image_panel_node.find('img:eq(0)').attr('src', ret.data.url);
        });

        controls.input_template_video_upload.fileinput({
            language: 'zh', //设置语言
            uploadUrl: $('#upload_host').text(), //上传的地址
            allowedFileExtensions: ['mp4'],//接收的文件后缀
            showUpload: false, //是否显示上传按钮
            showCaption: false,//是否显示标题,
            showRemove: false,
            uploadAsync: true,
            browseClass: "btn btn-primary", //按钮样式
            uploadExtraData:function() {
                var dataObj = {};
                dataObj.key = 'user/publish/'+ new Date().getTime() + Math.floor(Math.random()*100000000)+'.mp4';
                dataObj.OSSAccessKeyId = G_UPLOAD_POLICY.OSSAccessKeyId;
                dataObj.host = G_UPLOAD_POLICY.host;
                dataObj.policy = G_UPLOAD_POLICY.policy;
                dataObj.signature = G_UPLOAD_POLICY.signature;
                dataObj.success_action_status = G_UPLOAD_POLICY.G_UPLOAD_POLICY;
                dataObj.callback = G_UPLOAD_POLICY.callback;
                dataObj.expire = G_UPLOAD_POLICY.expire;
                return dataObj;
            }
        }).on("filebatchselected", function (event, files) {
            controls.input_template_video_upload.fileinput("upload");
        }).on("fileuploaded", function (event, data, previewId, index) {
            console.log(data);
            var ret = data.response;
            if (ret.status != 0) {
                return commonUtil.toast(ret.msg);
            }
            G_TEMPLATE_VIDEO_URL = ret.data.url;
        });

        controls.input_template_style_upload.fileinput({
            language: 'zh', //设置语言
            uploadUrl: '/admin/file/upload-to-ali-oss', //上传的地址
            allowedFileExtensions: ['jpg', 'jpeg', 'png', 'gif'],//接收的文件后缀
            showUpload: false, //是否显示上传按钮
            showCaption: false,//是否显示标题,
            showRemove: false,
            uploadAsync: true,
            browseClass: "btn btn-primary", //按钮样式
        }).on("filebatchselected", function (event, files) {
            controls.input_template_style_upload.fileinput("upload");
        }).on("fileuploaded", function (event, data, previewId, index) {
            console.log(data);
            var ret = data.response;
            if (ret.status != 0) {
                return commonUtil.toast(ret.msg);
            }
            G_TEMPLATE_STYLE_IMAGE_URL = ret.data.url;
        });

        controls.input_template_upload.fileinput({
            language: 'zh', //设置语言
            uploadUrl: '/admin/file/upload', //上传的地址
            allowedFileExtensions: ['zip'],//接收的文件后缀
            showUpload: false, //是否显示上传按钮
            showCaption: false,//是否显示标题,
            showRemove: false,
            uploadAsync: true,
            maxFileCount: 1,
            uploadExtraData: function () {
                var styles = G_CURRENT_DATA_TEMPLATE ? JSON.parse(G_CURRENT_DATA_TEMPLATE.styles || '[]') : [];
                var upload_info = null;
                let fid = '';
                if (styles.length <= 0) {
                    upload_info = controls.app_scene_detail_panel.find('.style-div').attr('upload_info') ? JSON.parse(decodeURIComponent(controls.app_scene_detail_panel.find('.style-div').attr('upload_info'))) : null;
                } else {
                    upload_info = controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').find('option:selected').attr('upload_info') ? JSON.parse(decodeURIComponent(controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').find('option:selected').attr('upload_info'))) : null;
                }

                return {
                    fid: upload_info && upload_info.id || '',
                }
            },
            browseClass: "btn btn-primary", //按钮样式
        }).on("filebatchselected", function (event, files) {
            controls.input_template_upload.fileinput("upload");
        }).on("fileuploaded", function (event, data, previewId, index) {
            let ret = data.response;
            if (ret.status != 0) {
                return commonUtil.toast(ret.msg);
            }

            ret.data.doc_id = $.trim($('#template_store_doc_id').val());

            var styles = JSON.parse(G_CURRENT_DATA_TEMPLATE.styles || '[]');
            if (styles.length <= 0) {
                controls.app_scene_detail_panel.find('.style-div').attr('upload_info', encodeURIComponent(JSON.stringify(ret.data)));
            } else {
                controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').find('option:selected').attr('upload_info', encodeURIComponent(JSON.stringify(ret.data)));
            }

            controls.app_scene_detail_panel.find('tbody:eq(0)').empty();

            ret.data.custom.text && ret.data.custom.text.forEach(function (item) {
                item.type = "文本";
                controls.app_scene_detail_panel.find('tbody:eq(0)').append(genSceneDetailDom(item))
            });
            ret.data.custom.color && ret.data.custom.color.forEach(function (item) {
                item.type = "颜色";
                controls.app_scene_detail_panel.find('tbody:eq(0)').append(genSceneDetailDom(item))
            });
            ret.data.custom.image && ret.data.custom.image.forEach(function (item) {
                item.type = "图片";
                controls.app_scene_detail_panel.find('tbody:eq(0)').append(genSceneDetailDom(item))
            });
            ret.data.custom.video && ret.data.custom.video.forEach(function (item) {
                item.type = "视频";
                controls.app_scene_detail_panel.find('tbody:eq(0)').append(genSceneDetailDom(item))
            });

            $('#template_store_position').text(ret.data.templateBase)


        });

        // 新增场景
        controls.app_scene_list_panel.find('button:eq(1)').bind('click', function () {
            showSceneDetailPanel();
            initSceneCategoryList();

            resetInputSceneData();
            G_MODIFY_SCENE = false;


        });

        // 场景查询
        controls.app_scene_list_panel.find('button:eq(2)').bind('click', function () {
            refreshSceneData();
        });

        // 返回场景列表
        controls.app_scene_detail_panel.find('button:eq(0)').bind('click', function () {
            showSceneListPanel();
            refreshSceneData();
        });

        $('#template_store_doc_id').bind('keyup', function () {
            var _self = this;
            var val = $(_self).val();

            if (val.length > 0) {
                var styles = JSON.parse(G_CURRENT_DATA_TEMPLATE.styles || '[]');
                if (styles.length <= 0) {
                    var div_upload_info = JSON.parse(decodeURIComponent(controls.app_scene_detail_panel.find('.style-div').attr('upload_info')));
                    if (div_upload_info) {
                        div_upload_info.doc_id = val;
                        controls.app_scene_detail_panel.find('.style-div').attr('upload_info', encodeURIComponent(JSON.stringify(div_upload_info)))
                    }
                } else {
                    controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').find('option').each(function () {
                        if (controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').val() == $(this).attr('value')) {

                            var data_info = JSON.parse(decodeURIComponent($(this).attr('upload_info') || "{}"));
                            data_info.doc_id = val;

                            $(this).attr('upload_info', encodeURIComponent(JSON.stringify(data_info)))
                        }

                    });
                }
            }

        });

        $('#btn_app_scene_detail_select').bind('click', function () {
            $('#app_scene_category_panel').modal('show');
        });

        controls.app_scene_category_panel.find('button:eq(1)').bind('click', function () {
            var keyword = $.trim(controls.app_scene_category_panel.find('input:eq(0)').val());
            $('#app_scene_category_panel_body').empty();
            G_ALL_SCENE_CATEGORY.forEach(function (item) {
                if (!!~item.val.indexOf(keyword)) {
                    $('#app_scene_category_panel_body').append('<div><input type="radio" name="scene_category_radio" value="' + item.val + '"/><span style="position: relative;top:-3px;">' + item.val + '</span></div>')
                }
            })
        });

        controls.app_scene_category_panel.find('button:eq(-2)').bind('click', function () {
            controls.app_scene_detail_panel.find('input[type=text]:eq(1)').val($('#app_scene_category_panel_body').find('input[type=radio]:checked').val() || '')
            $('#app_scene_category_panel').modal('hide');
        });

        // 场景修改
        controls.app_scene_detail_panel.find('button:eq(-1)').bind('click', function () {
            var args = {};

            var title = $.trim(controls.app_scene_detail_panel.find('input[type=text]:eq(0)').val());
            if (!title) return commonUtil.toast('标题不能为空');
            args.title = title;

            args.category = $.trim(controls.app_scene_detail_panel.find('input[type=text]:eq(1)').val());//controls.app_scene_detail_panel.find('select:eq(0)').val();
            args.type =  controls.app_scene_detail_panel.find('select:eq(2)').val();

            if (!args.category) {
                return commonUtil.toast('场景分类不能为空');
            }

            var min_time = $.trim($('#scene_min_time_input').val());
            if(min_time) {
                if(!validationUtil.isPositiveWholeNumber(min_time)) {
                    return commonUtil.toast('最小时常必须是正整数');
                }

                args.min_time = min_time;
            }


            var style = [];
            var styles = JSON.parse(G_CURRENT_DATA_TEMPLATE.styles || '[]');
            if (styles.length <= 0) {
                var div_upload_info = decodeURIComponent(controls.app_scene_detail_panel.find('.style-div').attr('upload_info'));
                if (div_upload_info) {
                    style.push({extra: JSON.parse(div_upload_info)})
                }
            } else {
                controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').find('option').each(function () {
                    style.push({
                        style_id: $(this).attr('value'),
                        style_name: $(this).text(),
                        extra: JSON.parse(decodeURIComponent($(this).attr('upload_info') || "{}"))
                    })
                });
            }
            var flag = false;
            for (var i = 0; i < style.length; i++) {
                if (style[i].extra && JSON.stringify(style[i].extra) != '{}') {
                    flag = true;
                }
            }
            if (!flag) {
                return commonUtil.toast('请上传场景模板文件')
            }

            var doc_id = [];
            style.forEach(function (s) {
                doc_id.push(s.extra.doc_id || '')
            });
            style.filter(function (s) {
                return s !== '';
            });

            args.music = JSON.stringify(G_SCENE_MUSIC);

            args.style = JSON.stringify(style);

            args.template_id = G_CURRENT_DATA_TEMPLATE.id;
            args.doc_id = doc_id.join('|');

            if (G_MODIFY_SCENE) {
                args.id = G_CURRENT_DATA_SCENE.id;
            }

            ajaxUtil.doAjaxPost(urls.scene_save, args).done(function (ret) {
                if (ret.status == 0) {
                    showSceneListPanel();
                    refreshSceneData();
                    resetInputSceneData();
                } else {
                    commonUtil.toast(ret.msg);
                }
            });
        });

        // 新增预置场景
        controls.app_scene_preset_list_panel.find('button:eq(0)').bind('click', function () {
            resetInputPresetData();
            G_MODIFY_PRESET = false;

            PRESET_VIDEO_URL = null;
            PRESET_IMAGE_URL = null;

            controls.app_scene_preset_detail_panel.modal('show');
            initListBox();
        });

        controls.template_style_edit.find('button:eq(1)').bind('click', function () {
            var result = $.trim(controls.template_style_edit.find('input:eq(0)').val());

            if (!result) return commonUtil.toast('请输入风格名称');

            if (!G_TEMPLATE_STYLE_IMAGE_URL) return commonUtil.toast('请上传风格缩略图')
            if (G_EDIT_ID) {
                controls.app_template_detail_panel.find('.style-name').each(function () {
                    var _self = this;

                    if ($(_self).attr('sid') == G_EDIT_ID) {
                        $(_self).attr('simage', G_TEMPLATE_STYLE_IMAGE_URL);
                        $(_self).next().find('img:eq(0)').attr('src', G_TEMPLATE_STYLE_IMAGE_URL);
                        $(_self).text(result)
                    }
                });
            } else {
                var sid = new Date().getTime();

                if (result) {
                    var _dom =
                        '    <tr>' +
                        '        <td class="style-name" simage="' + G_TEMPLATE_STYLE_IMAGE_URL + '" sid="' + sid + '">' + result + '</td>' +
                        '<td><img style="width: 50px;height: 80px;" src="' + G_TEMPLATE_STYLE_IMAGE_URL + '"/></td>' +
                        '        <td ><span class="style-edit">编辑</span>&nbsp;&nbsp;<span class="style-delete">删除</span></td>' +
                        '    </tr>';
                    controls.app_template_detail_panel.find('tbody:eq(0)').append(_dom);
                }
            }

            controls.template_style_edit.find('button:eq(0)').trigger('click');
        });

        controls.template_style_edit.find('button:eq(0)').bind('click', function () {
            showStyleList();
            controls.template_style_edit.find('input:eq(0)').val('');
            G_TEMPLATE_STYLE_IMAGE_URL = null;
            G_DEIT_STYLE = false;
            G_EDIT_ID = null;
        });

        // 模板编辑添加风格
        controls.app_template_detail_panel.find('button:eq(-3)').bind('click', function () {
            showStyleEdit();
        });

        // 模板编辑删除风格
        controls.app_template_detail_panel.find('tbody:eq(0)').on({
            'click': function () {
                $(this).parent().remove();
            }
        }, '.style-delete');

        controls.app_template_detail_panel.find('tbody:eq(0)').on({
            'click': function () {
                showStyleEdit();
                controls.template_style_edit.find('input:eq(0)').val($(this).parent().parent().find('td:eq(0)').text());
                G_TEMPLATE_STYLE_IMAGE_URL = $(this).parent().parent().find('td:eq(0)').attr('simage');
                G_DEIT_STYLE = true;
                G_EDIT_ID = $(this).parent().parent().find('td:eq(0)').attr('sid');
            }
        }, '.style-edit');

        // 预置场景保存
        controls.app_scene_preset_detail_panel.find('button:eq(-2)').bind('click', function () {
            var args = {};

            var title = $.trim(controls.app_scene_preset_detail_panel.find('input[type=text]:eq(0)').val());
            if (!title) return commonUtil.toast('标题不能为空');
            args.title = title;

            var des = $.trim(controls.app_scene_preset_detail_panel.find('textarea:eq(0)').val());
            if (!des) return commonUtil.toast('说明不能为空');
            args.des = des;

            args.template_id = G_CURRENT_DATA_TEMPLATE.id;

            if (!PRESET_IMAGE_URL) {
                return commonUtil.toast('请上传缩略图');
            }

            args.img_url = PRESET_IMAGE_URL;

            if (!PRESET_VIDEO_URL) {
                return commonUtil.toast('请上传演示视频');
            }

            args.video_url = PRESET_VIDEO_URL;

            var scene_detail = [];

            $('#preset_list_box_switch').find('select:eq(1)').find('option').each(function () {
                scene_detail.push({id: $(this).attr('value'), title: $(this).text()});
            });

            args.scene_detail = JSON.stringify(scene_detail);

            if (G_MODIFY_PRESET) {
                args.id = G_CURRENT_DATA_PRESET.id;
            }

            ajaxUtil.doAjaxPost(urls.preset_save, args).done(function (ret) {
                if (ret.status == 0) {
                    controls.app_scene_preset_detail_panel.modal('hide');
                    refreshPresetData();
                } else {
                    commonUtil.toast(ret.msg);
                }
            });


        });

        // 预置场景修改
        $("#app_scene_preset_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));

                G_MODIFY_PRESET = true;
                G_CURRENT_DATA_PRESET = data;

                resetInputPresetData();
                controls.app_scene_preset_detail_panel.modal('show');

                PRESET_VIDEO_URL = data.video_url;
                PRESET_IMAGE_URL = data.img_url;

                initListBox(data.scene_detail);

                controls.app_scene_preset_detail_panel.find('input[type=text]:eq(0)').val(data.title);
                controls.app_scene_preset_detail_panel.find('textarea:eq(0)').val(data.des)
            }
        }, '.resource-modify');

        // 点击删除预置场景
        $("#app_scene_preset_list_grid").on({
            'click': function () {
                var data = JSON.parse(decodeURIComponent($(this).data('user')));
                bootbox.confirm({
                    title: "温馨提示",
                    message: "确认删除？",
                    buttons: {
                        cancel: {
                            label: '<i class="fa fa-times"></i> 取消'
                        },
                        confirm: {
                            label: '<i class="fa fa-check"></i> 确认'
                        }
                    },
                    callback: function (result) {
                        if (result) {
                            var args = {};
                            args.id = data.id;
                            ajaxUtil.doAjaxGet(urls.preset_del, args).done(function (ret) {
                                if (ret.status == 0) {
                                    refreshPresetData();
                                } else {
                                    commonUtil.toast(ret.msg);
                                }

                            });
                        }
                    }
                });
            }
        }, '.resource-delete');
    }


    function loadModelDataSceneCategory(data) {
        data = data || {};

        if (G_IS_SCENE_CATETORY_LOAD) {
            var page = $("#app_scene_category_list_grid").getGridParam('page'); // current page
            var rows = $("#app_scene_category_list_grid").getGridParam('rows'); // rows
            $("#app_scene_category_list_grid").jqGrid('setGridParam', {
                postData: data,
                page: page,
                rows: rows
            }).trigger("reloadGrid")
        } else {
            $("#app_scene_category_list_grid").jqGrid({
                colModel: [
                    {
                        label: '场景分类名称',
                        name: 'val',
                        align: 'center',
                        formatter: function (cellValue, options, rowObject) {
                            return '<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-modify" style="color: #01AAED;">' + cellValue + '</a>&nbsp;&nbsp;'
                        }
                    },
                    {
                        label: '创建时间',
                        name: 'create_time',
                        align: 'center',
                        formatter: function (cellValue, options, rowObject) {
                            return commonUtil.getTimeString(cellValue);

                        }
                    },
                    {
                        label: '操作', align: 'center', formatter: function (cellValue, options, rowObject) {
                            return '<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-delete" style="color: #01AAED;">删除</a>'
                        }
                    }
                ],
                styleUI: 'Bootstrap',
                datatype: 'json',
                url: urls.list,
                rowNum: 10,
                rowList: [10, 20, 30],
                viewrecords: true, // show the current page, data rang and total records on the toolbar
                height: true,
                fitColumns: true,
                postData: data,
                width: true,
                autowidth: true,
                shrinkToFit: true,
                ajaxGridOptions: {
                    dataFilter: function (ret) {
                        var retObj = JSON.parse(ret);
                        if (retObj.status == 0) {
                            return JSON.stringify(retObj.data);
                        } else {
                            commonUtil.toast(retObj.msg);
                        }
                    }
                },
                pager: "#app_scene_category_list_grid_pager"
            });
            // 初始化宽宽，用于自适应宽度
            $("#app_scene_category_list_grid").setGridWidth($("#page-wrapper").width(), true);

            G_IS_SCENE_CATETORY_LOAD = true;
        }


    }


    function resetInputSceneCategory() {
        controls.app_scene_category_detail_panel.find('input[type=text]:eq(0)').val('');
    }

    function showStyleList() {
        controls.template_style_edit.hide();
        controls.template_style_list.show();
    }

    function showStyleEdit() {
        controls.template_style_edit.show();
        controls.template_style_list.hide();
    }

    function refreshTemplateData(data) {
        data = data || {};

        data.title = $.trim(controls.app_template_list_panel.find('input[type=text]:eq(0)').val());
        var category = $.trim(controls.app_template_list_panel.find('select:eq(0)').val());

        if (category != '-1') {
            data.category = category;
        } else {
            data.category = '';
        }

        var page = $("#app_template_list_grid").getGridParam('page'); // current page
        var rows = $("#app_template_list_grid").getGridParam('rows'); // rows
        $("#app_template_list_grid").jqGrid('setGridParam', {
            postData: data,
            page: page,
            rows: rows
        }).trigger("reloadGrid")
    }

    function loadTemplateData() {
        $("#app_template_list_grid").jqGrid({
            colModel: [
                {
                    label: '标题', name: 'title', align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        return '<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-modify" style="color: #01AAED;">' + cellValue + '</a>'
                    }
                },
                {
                    label: '场景数', name: 'sence_count', align: 'center', width: 40,
                    formatter: function (cellValue, options, rowObject) {
                        return '<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-scene" style="color: #01AAED;">' + cellValue + '</a>'
                    }
                },
                {label: '导出次数', name: 'export_count', align: 'center', width: 40,},
                // {
                //     label: '是否包含视频', name: 'export_count', align: 'center',
                //     formatter: function (cellValue, options, rowObject) {
                //         return cellValue == 0 ? "否" : "是"
                //
                //     }
                // },
                {
                    label: '时间',
                    name: 'create_time',
                    align: 'center',
                    width: 100,
                    formatter: function (cellValue, options, rowObject) {
                        return commonUtil.getTimeString(cellValue);
                    }
                },
                {
                    label: '分类', name: 'categories', align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        var data = JSON.parse(cellValue);

                        console.log(data);
                        var ctx = [];
                        for (var i = 0; i < data.length; i++) {
                            ctx.push(data[i].val);
                        }

                        return ctx.join(',');
                    }
                },
                {label: '收藏数', name: 'favorite_count', align: 'center', width: 40,},
                {
                    label: '操作', name: 'opera', align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        var dom = '<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-scene-category" style="color: #01AAED;">场景分类管理</a>&nbsp;&nbsp;<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-color" style="color: #01AAED;">颜色管理</a>';
                        if (rowObject.is_publish) {
                            dom += '&nbsp;&nbsp;<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-publish" style="color: #01AAED;">下架</a>';

                        } else {
                            dom += '&nbsp;&nbsp;<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-publish" style="color: #01AAED;">上架</a>';

                        }

                        dom += '&nbsp;&nbsp;<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-delete" style="color: #01AAED;">删除</a>';

                        return dom;
                    }
                }
            ],
            styleUI: 'Bootstrap',
            datatype: 'json',
            url: urls.template_list,
            rowNum: 10,
            rowList: [10, 20, 30],
            viewrecords: true, // show the current page, data rang and total records on the toolbar
            height: true,
            fitColumns: true,
            width: true,
            autowidth: true,
            shrinkToFit: true,
            ajaxGridOptions: {
                dataFilter: function (ret) {
                    var retObj = JSON.parse(ret);
                    if (retObj.status == 0) {
                        return JSON.stringify(retObj.data);
                    } else {
                        commonUtil.toast(retObj.msg);
                    }
                }
            },
            pager: "#app_template_list_grid_pager"
        });
        // 初始化宽宽，用于自适应宽度
        $("#app_template_list_grid").setGridWidth($("#page-wrapper").width(), true);
    }

    function refreshSceneData(data) {
        data = data || {};

        data.title = $.trim(controls.app_scene_list_panel.find('input[type=text]:eq(0)').val());
        var category = $.trim(controls.app_scene_list_panel.find('select:eq(0)').val());

        data.template_id = G_CURRENT_DATA_TEMPLATE.id;

        if (category != '-1') {
            data.category = category;
        } else {
            data.category = '';
        }

        var page = $("#app_scene_list_grid").getGridParam('page'); // current page
        var rows = $("#app_scene_list_grid").getGridParam('rows'); // rows
        $("#app_scene_list_grid").jqGrid('setGridParam', {
            postData: data,
            page: page,
            rows: rows
        }).trigger("reloadGrid")
    }

    function loadSceneData() {
        $("#app_scene_list_grid").jqGrid({
            colModel: [
                {
                    label: '标题', name: 'title', align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        return '<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-modify" style="color: #01AAED;">' + cellValue + '</a>'
                    }
                },
                {
                    label: '长度是否可调整', name: 'length_adjustable', align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        return cellValue == 0 ? "否" : "是";
                    }
                },
                {
                    label: '是否包含视频', name: 'has_video', align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        return cellValue == 0 ? "否" : "是";
                    }
                },
                {
                    label: '分类', name: 'category', align: 'center',width:50,
                },
                {
                    label: '时长', name: 'during', align: 'center',width:50,
                },
                {
                    label: '上传时间',
                    name: 'create_time',
                    align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        return commonUtil.getTimeString(cellValue);
                    }
                },
                {
                    label: '类型',
                    name: 'type',
                    align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        if(cellValue == 0) {
                            return '正常场景'
                        } else if (cellValue == 1) {
                            return '入场动画'
                        } else if (cellValue == 2) {
                            return '出场动画'
                        }
                    }
                },
                {
                    label: '状态', name: 'status', align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        if (cellValue == 0) {
                            return '<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-status" style="color: #01AAED;">需重新渲染</a>'
                        } else {
                            return '<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-render-success" style="color: #01AAED;">渲染完成</a>'
                        }

                    }
                },
                {
                    label: '渲染状态', name: '', align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        return '<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-status-render" style="color: #01AAED;">-</a>'
                    }
                },
                {
                    label: '操作', name: 'opera', align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        return '<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-preview-set" style="color: #01AAED;">预览图调整</a>&nbsp;&nbsp;<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-delete" style="color: #01AAED;">删除</a>'
                    }
                }
            ],
            styleUI: 'Bootstrap',
            datatype: 'json',
            url: urls.scene_list,
            rowNum: 10,
            rowList: [10, 20, 30],
            viewrecords: true, // show the current page, data rang and total records on the toolbar
            height: true,
            fitColumns: true,
            width: true,
            autowidth: true,
            shrinkToFit: true,
            ajaxGridOptions: {
                dataFilter: function (ret) {
                    var retObj = JSON.parse(ret);
                    if (retObj.status == 0) {
                        return JSON.stringify(retObj.data);
                    } else {
                        commonUtil.toast(retObj.msg);
                    }
                }
            },
            pager: "#app_scene_list_grid_pager"
        });
        // 初始化宽宽，用于自适应宽度
        $("#app_scene_list_grid").setGridWidth($("#page-wrapper").width(), true);
    }

    function resetInputTemplateData() {
        controls.app_template_detail_panel.find('input[type=text]:eq(0)').val('');
        controls.app_template_detail_panel.find('input[type=text]:eq(1)').val('');
        controls.app_template_detail_panel.find('textarea:eq(0)').val('');
        controls.app_template_detail_panel.find('textarea:eq(1)').val('');
        controls.app_template_detail_panel.find('textarea:eq(2)').val('');

        controls.app_template_detail_panel.find('tbody:eq(0)').empty();
        controls.app_template_detail_panel.find('input[type=text]:eq(1)').val('');

        controls.input_template_banner_upload.fileinput("clear");
        controls.input_template_video_upload.fileinput("clear");
        controls.input_template_image_upload.fileinput("clear");
        G_TEMPLATE_BANNER_URL = null;
        G_TEMPLATE_VIDEO_URL = null;
        G_TEMPLATE_IMAGE_URL = null;

        //新增时重置版权为无版权
        // controls.copyright_select.val(0);
        // controls.copyright_select.trigger('change');

        controls.template_tool_type.val(0);
        controls.template_tool_type.trigger('change');

        controls.scene_preset_lock.val(1);
        controls.scene_preset_lock.trigger('changer');
    }


    function resetInputSceneData() {
        controls.app_scene_detail_panel.find('input[type=text]:eq(0)').val('');
        $('#scene_min_time_input').val(1);
        controls.app_scene_detail_panel.find('input[type=text]:eq(1)').val('');
        controls.app_scene_detail_panel.find('select:eq(0)').val(0);
        controls.app_scene_detail_panel.find('select:eq(2)').val(0);
        controls.input_template_upload.fileinput("clear");
        controls.input_template_music_upload.fileinput("clear");
        controls.app_scene_detail_panel.find('tbody:eq(0)').empty();
        controls.app_scene_detail_panel.find('tbody:eq(1)').empty();
        G_SCENE_MUSIC = [];

        $('#template_store_doc_id').val('');
        $('#template_store_position').text('');

        var styles = JSON.parse(G_CURRENT_DATA_TEMPLATE.styles || '[]');
        controls.app_scene_detail_panel.find('.style-div').attr('upload_info', '');
        if (styles.length <= 0) {
            controls.app_scene_detail_panel.find('.style-div').hide();
        } else {
            controls.app_scene_detail_panel.find('.style-div').show();
            controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').empty();

            for (var i = 0; i < styles.length; i++) {
                controls.app_scene_detail_panel.find('.style-div').find('select:eq(0)').append('<option value="' + styles[i].id + '">' + styles[i].name + '</option>');
            }
        }
    }

    function refreshPresetData(data) {
        data = data || {};

        data.template_id = G_CURRENT_DATA_TEMPLATE.id;

        var page = $("#app_scene_preset_list_grid").getGridParam('page'); // current page
        var rows = $("#app_scene_preset_list_grid").getGridParam('rows'); // rows
        $("#app_scene_preset_list_grid").jqGrid('setGridParam', {
            postData: data,
            page: page,
            rows: rows
        }).trigger("reloadGrid")
    }

    function loadPresetData() {
        $("#app_scene_preset_list_grid").jqGrid({
            colModel: [
                {
                    label: '标题', name: 'title', align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        return '<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-modify" style="color: #01AAED;">' + cellValue + '</a>'
                    }
                },
                {
                    label: '场景数', name: 'sence_count', align: 'center',
                },
                {label: '使用次数', name: 'use_count', align: 'center'},

                {
                    label: '创建时间',
                    name: 'create_time',
                    align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        return commonUtil.getTimeString(cellValue);
                    }
                },
                {
                    label: '操作', name: 'opera', align: 'center',
                    formatter: function (cellValue, options, rowObject) {
                        return '<a data-user="' + encodeURIComponent(JSON.stringify(rowObject)) + '" href="javascript:;" class="resource-delete" style="color: #01AAED;">删除</a>'
                    }
                }
            ],
            styleUI: 'Bootstrap',
            datatype: 'json',
            url: urls.preset_list,
            rowNum: 10,
            rowList: [10, 20, 30],
            viewrecords: true, // show the current page, data rang and total records on the toolbar
            height: true,
            fitColumns: true,
            width: true,
            autowidth: true,
            shrinkToFit: true,
            ajaxGridOptions: {
                dataFilter: function (ret) {
                    var retObj = JSON.parse(ret);
                    if (retObj.status == 0) {
                        return JSON.stringify(retObj.data);
                    } else {
                        commonUtil.toast(retObj.msg);
                    }
                }
            },
            pager: "#app_scene_preset_list_grid_pager"
        });
        // 初始化宽宽，用于自适应宽度
        $("#app_scene_preset_list_grid").setGridWidth($("#page-wrapper").width(), true);
    }

    function resetInputPresetData() {
        PRESET_IMAGE_URL = null;
        PRESET_VIDEO_URL = null;

        controls.app_scene_preset_detail_panel.find('input[type=text]:eq(0)').val('');
        controls.app_scene_preset_detail_panel.find('textarea:eq(0)').val('');
    }

    function getTransform(from, to) {
        var A, H, b, h, i, k, k_i, l, lhs, m, ref, rhs;
        console.assert((from.length === (ref = to.length) && ref === 4));
        A = []; // 8x8
        for (i = k = 0; k < 4; i = ++k) {
            A.push([from[i].x, from[i].y, 1, 0, 0, 0, -from[i].x * to[i].x, -from[i].y * to[i].x]);
            A.push([0, 0, 0, from[i].x, from[i].y, 1, -from[i].x * to[i].y, -from[i].y * to[i].y]);
        }

        b = []; // 8x1
        for (i = l = 0; l < 4; i = ++l) {
            b.push(to[i].x);
            b.push(to[i].y);
        }

        // Solve A * h = b for h
        h = numeric.solve(A, b);
        H = [[h[0], h[1], 0, h[2]], [h[3], h[4], 0, h[5]], [0, 0, 1, 0], [h[6], h[7], 0, 1]];
        // Sanity check that H actually maps `from` to `to`
        for (i = m = 0; m < 4; i = ++m) {
            lhs = numeric.dot(H, [from[i].x, from[i].y, 0, 1]);
            k_i = lhs[3];
            rhs = numeric.dot(k_i, [to[i].x, to[i].y, 0, 1]);
            console.assert(numeric.norm2(numeric.sub(lhs, rhs)) < 1e-9, "Not equal:", lhs, rhs);
        }

        return H;
    };

    function getRandomColor() {
        return '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).slice(-6);
    }

    function applyTransform(element, originalPos, targetPos, callback) {
        var H, from, i, j, p, to;
        // All offsets were calculated relative to the document
        // Make them relative to (0, 0) of the element instead
        from = (function () {
            var k, len, results;
            results = [];
            for (k = 0, len = originalPos.length; k < len; k++) {
                p = originalPos[k];
                results.push({
                    x: p[0] - originalPos[0][0],
                    y: p[1] - originalPos[0][1]
                });
            }

            return results;
        })();
        to = (function () {
            var k, len, results;
            results = [];
            for (k = 0, len = targetPos.length; k < len; k++) {
                p = targetPos[k];
                results.push({
                    x: p[0] - originalPos[0][0],
                    y: p[1] - originalPos[0][1]
                });
            }

            return results;
        })();
        // Solve for the transform
        H = getTransform(from, to);

        // Apply the matrix3d as H transposed because matrix3d is column major order
        // Also need use toFixed because css doesn't allow scientific notation
        $(element).css({
            'transform': `matrix3d(${((function () {
                var k, results;
                results = [];
                for (i = k = 0; k < 4; i = ++k) {
                    results.push((function () {
                        var l, results1;
                        results1 = [];
                        for (j = l = 0; l < 4; j = ++l) {
                            results1.push(H[j][i].toFixed(20));
                        }

                        return results1;
                    })());
                }

                return results;
            })()).join(',')})`,
            'transform-origin': '0 0'
        });
        return typeof callback === "function" ? callback(element, H) : void 0;
    };

    function addPolygon() {
        console.log('polygons before', polygons);

        var options = {selectable: true, objectCaching: false, stroke: 'red', fill: '#ff3f3b',opacity:0.6};

        if (G_POINTS.image && G_POINTS.image.length > 0) {
            var polys = [];
            for (var gpi = 0; gpi < G_POINTS.image.length; gpi++) {
                var polygonPoints = [];
                for (var i = 0; i < G_POINTS.image[gpi].length; i++) {

                    polygonPoints.push({x: G_POINTS.image[gpi][i].x, y: G_POINTS.image[gpi][i].y});
                }

                options.fill = 'red';
                options.name = 'image_' + gpi;

                var poly = new fabric.Polygon(polygonPoints, options);

                poly.on('modified', function (e) {
                    var name = this.get('name');
                    console.log('----------------modify', name);
                    var matrix = this.calcTransformMatrix();
                    console.log('----------------matrix', matrix);
                    var transformedPoints = this.get("points")
                        .map(function (p) {
                            return new fabric.Point(p.x - polygons.image[name.split('_')[1]].minX - polygons.image[name.split('_')[1]].width / 2, p.y - polygons.image[name.split('_')[1]].minY - polygons.image[name.split('_')[1]].height / 2);
                        })
                        .map(function (p) {
                            return fabric.util.transformPoint(p, matrix);
                        });

                    console.log('transformedPoints', transformedPoints);

                    for (var i = 0; i < transformedPoints.length; i++) {
                        var point = G_POINTS.image[name.split('_')[1]][i];
                        if (!point.oriX)
                            point.oriX = point.x;
                        if (!point.oriY)
                            point.oriY = point.y;

                        G_POINTS.image[name.split('_')[1]][i].x = transformedPoints[i].x;
                        G_POINTS.image[name.split('_')[1]][i].y = transformedPoints[i].y;
                    }

                    console.log('G_POINTS moved', G_POINTS);

                    canvas.clear();
                    addPolygon();
                    addControlPoints();
                    canvas.setActiveObject(polygons.image[name.split('_')[1]]);
                });

                polys.push(poly)
            }

            polygons.image = polys;

            polygons.image.forEach(function (polygon) {
                canvas.add(polygon);
                canvas.sendToBack(polygon);
            })
        }

        if (G_POINTS.video && G_POINTS.video.length > 0) {
            var polys = [];
            for (var gpi = 0; gpi < G_POINTS.video.length; gpi++) {
                var polygonPoints = [];
                for (var i = 0; i < G_POINTS.video[gpi].length; i++) {
                    polygonPoints.push({x: G_POINTS.video[gpi][i].x, y: G_POINTS.video[gpi][i].y});
                }
                options.fill = 'green'
                options.name = 'video_' + gpi;
                var poly = new fabric.Polygon(polygonPoints, options);

                poly.on('modified', function (e) {
                    var name = this.get('name');
                    console.log('----------------modify', name);
                    var matrix = this.calcTransformMatrix();
                    var transformedPoints = this.get("points")
                        .map(function (p) {
                            return new fabric.Point(p.x - polygons.video[name.split('_')[1]].minX - polygons.video[name.split('_')[1]].width / 2, p.y - polygons.video[name.split('_')[1]].minY - polygons.video[name.split('_')[1]].height / 2);
                        })
                        .map(function (p) {
                            return fabric.util.transformPoint(p, matrix);
                        });

                    for (var i = 0; i < transformedPoints.length; i++) {
                        var point = G_POINTS.video[name.split('_')[1]][i];
                        if (!point.oriX)
                            point.oriX = point.x;
                        if (!point.oriY)
                            point.oriY = point.y;

                        G_POINTS.video[name.split('_')[1]][i].x = transformedPoints[i].x;
                        G_POINTS.video[name.split('_')[1]][i].y = transformedPoints[i].y;
                    }

                    canvas.clear();
                    addPolygon();
                    addControlPoints();
                    canvas.setActiveObject(polygons.video[name.split('_')[1]]);
                });

                polys.push(poly)
            }

            polygons.video = polys;

            polygons.video.forEach(function (polygon) {
                canvas.add(polygon);
                canvas.sendToBack(polygon);
            })
        }

        if (G_POINTS.text && G_POINTS.text.length > 0) {
            var polys = [];

            for (var gpi = 0; gpi < G_POINTS.text.length; gpi++) {
                var polygonPoints = [];
                for (var i = 0; i < G_POINTS.text[gpi].length; i++) {
                    polygonPoints.push({x: G_POINTS.text[gpi][i].x, y: G_POINTS.text[gpi][i].y});
                }

                options.fill='blue'
                options.name = 'text_' + gpi;
                var poly = new fabric.Polygon(polygonPoints, options);

                poly.on('modified', function (e) {
                    var name = this.get('name');
                    console.log('----------------modify', name);
                    var matrix = this.calcTransformMatrix();
                    var transformedPoints = this.get("points")
                        .map(function (p) {
                            return new fabric.Point(p.x - polygons.text[name.split('_')[1]].minX - polygons.text[name.split('_')[1]].width / 2, p.y - polygons.text[name.split('_')[1]].minY - polygons.text[name.split('_')[1]].height / 2);
                        })
                        .map(function (p) {
                            return fabric.util.transformPoint(p, matrix);
                        });

                    for (var i = 0; i < transformedPoints.length; i++) {

                        var point = G_POINTS.text[name.split('_')[1]][i];
                        if (!point.oriX)
                            point.oriX = point.x;
                        if (!point.oriY)
                            point.oriY = point.y;

                        G_POINTS.text[name.split('_')[1]][i].x = transformedPoints[i].x;
                        G_POINTS.text[name.split('_')[1]][i].y = transformedPoints[i].y;
                    }

                    canvas.clear();
                    addPolygon();
                    addControlPoints();
                    canvas.setActiveObject(polygons.text[name.split('_')[1]]);
                });

                polys.push(poly)
            }

            polygons.text = polys;

            polygons.text.forEach(function (polygon) {
                canvas.add(polygon);
                canvas.sendToBack(polygon);
            })
        }

        console.log('polygons after', polygons);
    }

    function addControlPoints() {
        if (G_POINTS.image) {
            G_POINTS.image.forEach(function (img, ii) {
                img.forEach(function (point, index) {
                    var circle = new fabric.Rect({
                        width: 8,
                        height: 8,
                        strokeWidth: 1,
                        fill: '#fff',
                        stroke: '#ff3f3b',
                        left: point.x,
                        top: point.y,
                        originX: 'center',
                        originY: 'center',
                        hasBorders: false,
                        hasControls: false,
                        name: 'image_' + ii + '_' + index,
                    });

                    canvas.add(circle);
                });
            })
        }

        if (G_POINTS.video) {
            G_POINTS.video.forEach(function (vid, ii) {
                vid.forEach(function (point, index) {
                    var circle = new fabric.Rect({
                        width: 8,
                        height: 8,
                        strokeWidth: 1,
                        fill: '#fff',
                        stroke: '#ff3f3b',
                        left: point.x,
                        top: point.y,
                        originX: 'center',
                        originY: 'center',
                        hasBorders: false,
                        hasControls: false,
                        name: 'video_' + ii + '_' + index,
                    });

                    canvas.add(circle);
                });
            })
        }

        if (G_POINTS.text) {
            G_POINTS.text.forEach(function (txt, ii) {
                txt.forEach(function (point, index) {
                    var circle = new fabric.Rect({
                        width: 8,
                        height: 8,
                        strokeWidth: 1,
                        fill: '#fff',
                        stroke: '#ff3f3b',
                        left: point.x,
                        top: point.y,
                        originX: 'center',
                        originY: 'center',
                        hasBorders: false,
                        hasControls: false,
                        name: 'text_' + ii + '_' + index,
                    });

                    canvas.add(circle);
                });
            })
        }
    }

    function updateControls(options) {
        var objType = options.target.get('type');
        if (objType == 'rect') {
            var p = options.target;

            let splitP = p.name.split('_');
            if (splitP[0] === 'image') {
                G_POINTS.image[splitP[1]][splitP[2]].x = p.getCenterPoint().x;
                G_POINTS.image[splitP[1]][splitP[2]].y = p.getCenterPoint().y;

                polygons.image[splitP[1]].points[splitP[2]] = {
                    x: p.getCenterPoint().x,
                    y: p.getCenterPoint().y
                };
                canvas.clear();
                addPolygon();
                addControlPoints();
            } else if (splitP[0] === 'video') {
                G_POINTS.video[splitP[1]][splitP[2]].x = p.getCenterPoint().x;
                G_POINTS.video[splitP[1]][splitP[2]].y = p.getCenterPoint().y;

                polygons.video[splitP[1]].points[splitP[2]] = {
                    x: p.getCenterPoint().x,
                    y: p.getCenterPoint().y
                };
                canvas.clear();
                addPolygon();
                addControlPoints();
            } else if (splitP[0] === 'text') {
                G_POINTS.text[splitP[1]][splitP[2]].x = p.getCenterPoint().x;
                G_POINTS.text[splitP[1]][splitP[2]].y = p.getCenterPoint().y;

                polygons.text[splitP[1]].points[splitP[2]] = {
                    x: p.getCenterPoint().x,
                    y: p.getCenterPoint().y
                };
                canvas.clear();
                addPolygon();
                addControlPoints();
            }
        }
    }

    function makeTransformable(selector, callback) {
        return $(selector).each(function (i, element) {
            var controlPoints, originalPos, p, position;
            // $(element).css('transform', $(element).css('transform'));

            // Add four dots to corners of `element` as control points
            controlPoints = (function () {
                var k, len, ref, results;
                ref = ['left top', 'left bottom', 'right top', 'right bottom'];
                results = [];
                for (k = 0, len = ref.length; k < len; k++) {
                    position = ref[k];
                    results.push($('<div>').css({
                        border: '10px solid black',
                        borderRadius: '10px',
                        cursor: 'move',
                        position: 'absolute',
                        zIndex: 100000
                    }).appendTo('#app_scene_preview_image_panel_node').position({
                        at: position,
                        of: element,
                        collision: 'none'
                    }));
                }

                return results;
            })();
            // Record the original positions of the dots
            originalPos = (function () {
                var k, len, results;
                results = [];
                for (k = 0, len = controlPoints.length; k < len; k++) {
                    p = controlPoints[k];
                    results.push([p.offset().left, p.offset().top]);
                }

                return results;
            })();

            // Transform `element` to match the new positions of the dots whenever dragged
            $(controlPoints).draggable({
                start: () => {
                    return $(element).css('pointer-events', 'none'); // makes dragging around iframes easier
                },
                drag: () => {
                    return applyTransform(element, originalPos, (function () {
                        var k, len, results;
                        results = [];
                        for (k = 0, len = controlPoints.length; k < len; k++) {
                            p = controlPoints[k];
                            results.push([p.offset().left, p.offset().top]);
                        }

                        return results;
                    })(), callback);
                },
                stop: () => {
                    applyTransform(element, originalPos, (function () {
                        var k, len, results;
                        results = [];
                        for (k = 0, len = controlPoints.length; k < len; k++) {
                            p = controlPoints[k];
                            results.push([p.offset().left, p.offset().top]);
                        }

                        return results;
                    })(), callback);
                    return $(element).css('pointer-events', 'auto');
                }
            });
            return element;
        });
    };

    exports.init = init;
});